How to List Tar Archive Contents in Python

Open a tar archive with the stdlib tarfile module and print each entry's type, size, and name.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

42 lines
Python 3.9+
import tarfile
from pathlib import Path

def list_tar_contents(archive_path):
    """List all entries in a tar archive."""
    entries = []
    with tarfile.open(archive_path, "r") as tar:
        for member in tar.getmembers():
            entry_type = "dir" if member.isdir() else "file"
            entries.append(f"{entry_type:5s} {member.size:>10d} {member.name}")
    return entries


if __name__ == "__main__":
    # Create a small example tar archive to demonstrate
    import io
    import tarfile as tf

    sample_data = {
        "README.txt": b"Welcome to the archive\n",
        "config.json": b'{"version": 1}\n',
        "scripts/": None,
        "scripts/run.py": b'print("Hello")\n',
    }

    archive_path = Path("example.tar")
    with tf.open(archive_path, "w") as tar:
        for name, content in sample_data.items():
            info = tf.TarInfo(name)
            if content is None:
                info.type = tf.DIRTYPE
                tar.addfile(info)
            else:
                info.size = len(content)
                tar.addfile(info, io.BytesIO(content))

    # Now list the contents
    for line in list_tar_contents(archive_path):
        print(line)

    # Cleanup
    archive_path.unlink()

Output

stdout
file       20 README.txt
file       18 config.json
dir         0 scripts/
file       15 scripts/run.py

How it works

The tarfile.open call opens the archive in read mode ("r"), which auto-detects compression. tar.getmembers() returns TarInfo objects for every entry, including directories. member.isdir() checks the entry type so you can label directories vs. files. member.size gives the byte size of file entries (0 for directories). The function returns a list of formatted strings, so callers can print or further process each entry. The with block guarantees the archive file handle is closed even if an error occurs.

Common mistakes

  • Using `getnames()` when you need file sizes or directory flags
  • Forgetting directories appear as members and need special handling
  • Opening with a hardcoded mode like `"w"` when you only need to read

Variations

  1. Use `tar.getnames()` for a simple list of names only
  2. Use `tar.extractall()` instead of listing to extract all content

Real-world use cases

  • Auditing a backup archive before restoring to check for unexpected files.
  • Inspecting a downloaded package tarball to verify structure before unpacking.
  • Building a file browser UI that needs to show archive contents without extracting.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.