On this page
tarfile
Prev: tabnanny | Up: stdlib_module | Next: tempfile
Rel: pickle, copyreg, shelve, marshal, dbm
Ref: docs.python.org — tarfile
Tags: #public #python3 #stdlib
Import
import tarfile
Overview
Reads and writes POSIX tar archives, including transparent .tar.gz (r:gz/w:gz), .tar.bz2, and .tar.xz compression. Always pass filter="data" to extractall() / extract() (Python 3.12+) to block path traversal (../), absolute paths, and unsafe symlinks.
Quick Start
import io
import tarfile
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tf:
payload = b"hello tar\n"
info = tarfile.TarInfo(name="notes/hello.txt")
info.size = len(payload)
tf.addfile(info, io.BytesIO(payload))
buf.seek(0)
with tarfile.open(fileobj=buf, mode="r:gz") as tf:
assert tf.getnames() == ["notes/hello.txt"]
assert tf.extractfile("notes/hello.txt").read() == b"hello tar\n"
Implementation Walkthrough
1. Safe Extraction of Untrusted Archives (filter="data")
from pathlib import Path
import tarfile
def safe_extract_tar(archive: Path, dest: Path) -> None:
dest.mkdir(parents=True, exist_ok=True)
with tarfile.open(archive, "r:*") as tf:
tf.extractall(path=dest, filter="data")
2. Streaming Inspection Without Extracting to Disk
import tarfile
from pathlib import Path
def list_tar_members(archive: Path) -> list[tuple[str, int]]:
with tarfile.open(archive, "r:*") as tf:
return [(m.name, m.size) for m in tf.getmembers() if m.isfile()]
Gotchas & Boundaries
- Never call
extractall()withoutfilter="data"on untrusted tarballs: Legacy tar extraction can overwrite arbitrary files via../or malicious symlinks. - Mode
"r:*"auto-detects compression (uncompressed, gzip, bz2, xz); use"r|*"for non-seekable streams (such as stdin or HTTP responses). extractfile(member)returnsNonefor directories or symlinks: Checkmember.isfile()before reading.- Bound total extracted bytes on untrusted archives to defend against compression bombs.
Common Functions
- tarfile.data_filter() —
data_filter(member, dest_path)—tarfile.data_filter()function. - tarfile.fully_trusted_filter() —
fully_trusted_filter(member, dest_path)—tarfile.fully_trusted_filter()function. - tarfile.is_tarfile() —
is_tarfile(name)— Return True if name points to a tar archive that we are able to handle, else return False. - tarfile.open() —
open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)— Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. - tarfile.tar_filter() —
tar_filter(member, dest_path)—tarfile.tar_filter()function.
Classes & Objects
- tarfile.AbsoluteLinkError —
tarfile.AbsoluteLinkErrorclass. (Methods:.add_note(),.with_traceback()) - tarfile.AbsolutePathError —
tarfile.AbsolutePathErrorclass. (Methods:.add_note(),.with_traceback()) - tarfile.CompressionError — Exception for unavailable compression methods. (Methods:
.add_note(),.with_traceback()) - tarfile.ExtractError — General exception for extract errors. (Methods:
.add_note(),.with_traceback()) - tarfile.FilterError —
tarfile.FilterErrorclass. (Methods:.add_note(),.with_traceback()) - tarfile.HeaderError — Base exception for header errors. (Methods:
.add_note(),.with_traceback()) - tarfile.LinkFallbackError —
tarfile.LinkFallbackErrorclass. (Methods:.add_note(),.with_traceback()) - tarfile.LinkOutsideDestinationError —
tarfile.LinkOutsideDestinationErrorclass. (Methods:.add_note(),.with_traceback()) - tarfile.OutsideDestinationError —
tarfile.OutsideDestinationErrorclass. (Methods:.add_note(),.with_traceback()) - tarfile.ReadError — Exception for unreadable tar archives. (Methods:
.add_note(),.with_traceback()) - tarfile.SpecialFileError —
tarfile.SpecialFileErrorclass. (Methods:.add_note(),.with_traceback()) - tarfile.StreamError — Exception for unsupported operations on stream-like TarFiles. (Methods:
.add_note(),.with_traceback()) - tarfile.TarError — Base exception. (Methods:
.add_note(),.with_traceback()) - tarfile.TarFile — The TarFile Class provides an interface to tar archives. (Methods:
.add(),.addfile(),.bz2open(),.chmod(),.chown(),.close()) - tarfile.TarInfo — Informational class which holds the details about an archive member given by a tar header block. (Methods:
.create_gnu_header(),.create_pax_global_header(),.create_pax_header(),.create_ustar_header(),.frombuf(),.fromtarfile())
Constants & Attributes
tarfile.DEFAULT_FORMAT(int) =2tarfile.ENCODING(str) ='utf-8'tarfile.GNU_FORMAT(int) =1tarfile.PAX_FORMAT(int) =2tarfile.USTAR_FORMAT(int) =0
Linked from
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tabnanny Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/tempfile Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/copyreg Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dbm Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/gzip links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/marshal Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/pickle Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/shelve Linked here; shared tags: #stdlib