On this page
zipfile
Prev: zipapp | Up: stdlib_module | Next: zipimport
Rel: pickle, copyreg, shelve, marshal, dbm
Ref: docs.python.org — zipfile
Tags: #public #python3 #stdlib
Import
import zipfile
Overview
Creates, inspects, and extracts .zip archives (ZipFile, ZipInfo, ZIP_DEFLATED, Path) using only the standard library. Reach for zipfile for portable cross-platform bundles, reading packaged .whl/.docx/.xlsx files, or streaming archive members in memory without extracting to disk.
Quick Start
import io
import zipfile
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
zf.writestr("hello.txt", "hello zip\n")
buf.seek(0)
with zipfile.ZipFile(buf, "r") as zf:
assert zf.namelist() == ["hello.txt"]
assert zf.read("hello.txt").decode("utf-8") == "hello zip\n"
Implementation Walkthrough
1. Safe Extraction with Path-Traversal & Zip-Bomb Guards
Unlike tarfile, zipfile.extractall() does not automatically cap total uncompressed bytes—validate member paths and cumulative sizes on untrusted archives:
from pathlib import Path
import zipfile
def safe_extract_zip(archive: Path, dest: Path, *, max_bytes: int = 50_000_000) -> None:
root = dest.resolve()
root.mkdir(parents=True, exist_ok=True)
total = 0
with zipfile.ZipFile(archive, "r") as zf:
for info in zf.infolist():
target = (root / info.filename).resolve()
if not target.is_relative_to(root):
raise ValueError(f"Unsafe zip path: {info.filename}")
total += info.file_size
if total > max_bytes:
raise ValueError("Archive exceeds max_bytes limit")
zf.extractall(root)
2. Pathlib-Style Archive Access (zipfile.Path)
import io
import zipfile
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("docs/index.md", "# Title\n")
buf.seek(0)
with zipfile.ZipFile(buf, "r") as zf:
p = zipfile.Path(zf, "docs/index.md")
assert p.read_text(encoding="utf-8") == "# Title\n"
Gotchas & Boundaries
- Default compression is
ZIP_STORED(no compression): Passcompression=zipfile.ZIP_DEFLATEDwhen you actually want smaller archives. - Check
info.file_sizeandtarget.is_relative_to(root)on untrusted.zipfiles to defend against zip bombs and Zip Slip path traversal. - ZIP encryption in
zipfileis legacy ZipCrypto (weak) and read-only: Do not rely onZipFile.setpassword()for real security.
Common Functions
- zipfile.is_zipfile() —
is_zipfile(filename)— Quickly see if a file is a ZIP file by checking the magic number.
Classes & Objects
- zipfile.BadZipFile —
zipfile.BadZipFileclass. (Methods:.add_note(),.with_traceback()) - zipfile.BadZipfile —
zipfile.BadZipfileclass. (Methods:.add_note(),.with_traceback()) - zipfile.error —
zipfile.errorclass. (Methods:.add_note(),.with_traceback()) - zipfile.LargeZipFile — Raised when writing a zipfile, the zipfile requires ZIP64 extensions and those extensions are disabled. (Methods:
.add_note(),.with_traceback()) - zipfile.Path — A :class:
importlib.resources.abc.Traversableinterface for zip files. (Methods:.exists(),.filename(),.glob(),.is_dir(),.is_file(),.is_symlink()) - zipfile.PyZipFile — Class to create ZIP archives with Python library files and packages. (Methods:
.close(),.comment(),.extract(),.extractall(),.getinfo(),.infolist()) - zipfile.ZipFile — Class with methods to open, read, write, close, list zip files. (Methods:
.close(),.comment(),.extract(),.extractall(),.getinfo(),.infolist()) - zipfile.ZipInfo — Class with attributes describing each file in the ZIP archive. (Methods:
.FileHeader(),.from_file(),.is_dir())
Constants & Attributes
zipfile.ZIP_BZIP2(int) =12zipfile.ZIP_DEFLATED(int) =8zipfile.ZIP_LZMA(int) =14zipfile.ZIP_STORED(int) =0zipfile.ZIP_ZSTANDARD(int) =93
Linked from
Related notes
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/zipapp Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/zipimport 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