On this page
  1. zipfile
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Safe Extraction with Path-Traversal & Zip-Bomb Guards
  7. 2. Pathlib-Style Archive Access (zipfile.Path)
  8. Gotchas & Boundaries
  9. Common Functions
  10. Classes & Objects
  11. Constants & Attributes

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

Common Functions

Classes & Objects

Constants & Attributes

Linked from

Related notes