TAR combines files and metadata into a stream; gzip or another layer can compress it. tarfile joins these steps with modes such as w:gz and lets you inspect members before writing them to disk.

Practical example

from pathlib import Path
import tarfile

Path("data").mkdir(exist_ok=True)
Path("data/result.txt").write_text("ok", encoding="utf-8")

with tarfile.open("backup.tar.gz", "w:gz") as archive:
    archive.add("data", arcname="data")

with tarfile.open("backup.tar.gz", "r:gz") as archive:
    print(archive.getnames())

TAR is not ZIP

TAR is common for backups and Unix distribution, while ZIP is often more interoperable on desktops. Use arcname to control layout and avoid storing the source's absolute tree.

Never extract blindly

TAR members may contain parent paths, links, and special file types. On supported versions, use the data extraction filter, plus an isolated directory, size limits, and a link policy. Use extractfile() when you only need to read one member.

Keep learning

Continue with Python zipfile: create and read ZIP archives and Python Pathlib: Complete Guide to File System Manipulation. A official Python documentation, accessed July 22, 2026, documents the API and behavior across versions.