zipfile creates and inspects ZIP archives without an external dependency. The format is useful for interchange because it keeps a tree of names and is widely supported.

Practical example

from pathlib import Path
from zipfile import ZIP_DEFLATED, ZipFile

source = Path("notes.txt")
source.write_text("release notes", encoding="utf-8")

with ZipFile("bundle.zip", "w", compression=ZIP_DEFLATED) as archive:
    archive.write(source, arcname="docs/notes.txt")

with ZipFile("bundle.zip") as archive:
    print(archive.namelist())

Creating a predictable ZIP

Set arcname so the archive does not leak absolute paths from the machine. Choose compression deliberately and use a with block so the central directory is finalized.

Safe extraction

Before extracting received content, reject absolute paths and ensure every resolved destination remains under the allowed directory. Limit entry count, total size, and expansion ratio too. A valid ZIP may still carry malicious data.

Keep learning

Continue with Python Pathlib: Complete Guide to File System Manipulation and Python shutil: Copy, Move, and Archive Files. A official Python documentation, accessed July 22, 2026, documents the API and behavior across versions.