Compression and Archives Modules

tarfile

Reads and creates tar archives, optionally compressed with gzip, bzip2 or LZMA. Inspect members with getmembers() and read regular files with extractfile(). For trusted, constrained extraction on 3.13 explicitly consider filter="data"; filters do not eliminate every risk, including resource exhaustion. The example never extracts to disk.

Formal Syntax & Structure

python syntaxpython
import tarfile

Return Value

module

Module namespace available through import; import is a statement, not a value-returning expression.

Working Example

Example Snippetpython
from io import BytesIOimport tarfilebuffer = BytesIO()with tarfile.open(fileobj=buffer, mode="w") as archive:    info = tarfile.TarInfo("note.txt")    info.size = 5    archive.addfile(info, BytesIO(b"ready"))buffer.seek(0)with tarfile.open(fileobj=buffer, mode="r:") as archive:    print(archive.getnames())    with archive.extractfile("note.txt") as stream:        print(stream.read())
Python Reference