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.
Python code
42 linesimport 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
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
- Use `tar.getnames()` for a simple list of names only
- 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
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.