Use Python’s built-in zipfile.ZipFile context manager (with zipfile.ZipFile("archive.zip") as zf: zf.extractall("output_dir"))—or shutil.unpack_archive("archive.zip", "output_dir") for a concise one-liner—while validating member paths first on untrusted archives to prevent Zip Slip path-traversal attacks.

Basic Example

from pathlib import Path
import shutil
import zipfile

archive_path = Path("data.zip")
dest_dir = Path("extracted_files")

# 1. Recommended (stdlib zipfile): Full control over inspection, filtering & passwords
with zipfile.ZipFile(archive_path, mode="r") as zf:
    print("Files in archive:", zf.namelist())
    zf.extractall(path=dest_dir)                  # Extract all files
    # zf.extract("reports/summary.csv", dest_dir) # Or extract a single member

# 2. One-liner alternative (auto-detects .zip, .tar, .tar.gz, .tar.bz2, .tar.xz):
shutil.unpack_archive(archive_path, extract_dir=dest_dir)

Key Details & Edge Cases

  • Always protect against “Zip Slip” path traversal on untrusted .zip files:
    • Malicious archives can contain member names like "../../.ssh/authorized_keys" or "/etc/cron.d/job". While ZipFile.extractall() strips leading slashes and .. components in modern Python versions, explicitly validating resolved target paths is still best practice for security-critical code:
      base = dest_dir.resolve()
      with zipfile.ZipFile(archive_path) as zf:
          for member in zf.infolist():
              target = (base / member.filename).resolve()
              if not target.is_relative_to(base):
                  raise ValueError(f"Unsafe path in archive: {member.filename}")
              zf.extract(member, base)
      
  • Guard against Zip Bombs (decompression exhaustion) on untrusted uploads:
    • Check total uncompressed size before extracting (total_size = sum(info.file_size for info in zf.infolist())) and abort if it exceeds a safe threshold (note that info.file_size comes from the ZIP header and can be spoofed, so enforce byte limits when streaming untrusted members with zf.open()).
  • Extracting password-protected (ZipCrypto) archives:
    • Pass pwd=b"secret" (must be bytes, not str) to zf.extractall(dest_dir, pwd=b"secret"). Note that Python’s built-in zipfile supports legacy ZipCrypto decryption only—for modern AES-256 encrypted .zip files (which raise NotImplementedError: That compression method is not supported), use pyzipper (pip install pyzipper).
  • Non-UTF-8 / garbled filenames created on Windows (metadata_encoding in Python 3.11+):
    • Archives zipped on non-English Windows systems often encode filenames in cp437 or cp932 without setting the UTF-8 flag. In Python 3.11+, pass zipfile.ZipFile(path, metadata_encoding="cp437") (or "utf-8") to prevent mojibake characters.
  • Inspecting or reading a file inside a .zip without writing it to disk:
    • Use zf.read("config.json") (returns bytes) or with zf.open("data.csv") as f: (returns a binary file-like stream—ideal for passing straight into pd.read_csv(zf.open("data.csv")) or io.TextIOWrapper(f, encoding="utf-8")).

Comparison of .zip Extraction Methods in Python

Method Module Supports Filtering / Single-File Extraction? Supports Passwords (pwd=)? Supports .tar.gz / .tar.xz Too? Best Used When
zipfile.ZipFile.extractall() (Recommended) zipfile (stdlib) Yes (members=, .extract()) Yes (ZipCrypto bytes) No (.zip only) Standard .zip extraction, security validation, and selective member unpacking.
shutil.unpack_archive() shutil (stdlib) No (extracts entire archive) No Yes (auto-detects format) Quick one-line extraction of trusted .zip or .tar.* archives to a folder.
zf.open() / zf.read() zipfile (stdlib) Yes (in-memory stream) Yes No Streaming CSV/JSON files inside a .zip directly into Pandas or json.load() without disk I/O.
pyzipper.AESZipFile pyzipper (3rd-party) Yes Yes (AES-128/256 + ZipCrypto) No Extracting modern AES-encrypted .zip archives created by 7-Zip or WinZip.