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
.zipfiles:- Malicious archives can contain member names like
"../../.ssh/authorized_keys"or"/etc/cron.d/job". WhileZipFile.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)
- Malicious archives can contain member names like
- 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 thatinfo.file_sizecomes from the ZIP header and can be spoofed, so enforce byte limits when streaming untrusted members withzf.open()).
- Check total uncompressed size before extracting (
- Extracting password-protected (ZipCrypto) archives:
- Pass
pwd=b"secret"(must bebytes, notstr) tozf.extractall(dest_dir, pwd=b"secret"). Note that Python’s built-inzipfilesupports legacy ZipCrypto decryption only—for modern AES-256 encrypted.zipfiles (which raiseNotImplementedError: That compression method is not supported), usepyzipper(pip install pyzipper).
- Pass
- Non-UTF-8 / garbled filenames created on Windows (
metadata_encodingin Python 3.11+):- Archives zipped on non-English Windows systems often encode filenames in
cp437orcp932without setting the UTF-8 flag. In Python 3.11+, passzipfile.ZipFile(path, metadata_encoding="cp437")(or"utf-8") to prevent mojibake characters.
- Archives zipped on non-English Windows systems often encode filenames in
- Inspecting or reading a file inside a
.zipwithout writing it to disk:- Use
zf.read("config.json")(returnsbytes) orwith zf.open("data.csv") as f:(returns a binary file-like stream—ideal for passing straight intopd.read_csv(zf.open("data.csv"))orio.TextIOWrapper(f, encoding="utf-8")).
- Use
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. |
You must log in or register to comment.
