On this page
  1. tarfile
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Extraction of Untrusted Archives (filter="data")
  7. 2. Streaming Inspection Without Extracting to Disk
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes