How do I create and extract ZIP archives in Python?

· Category: Python Programming

Short answer

The zipfile module lets you read and write ZIP archives without external tools. Use ZipFile.write() to add files and ZipFile.extractall() to unpack them.

Steps

  1. Open a ZipFile in write mode (w) or append mode (a).
  2. Add files with .write() or .writestr().
  3. Extract with .extractall() or iterate over .namelist().
from zipfile import ZipFile
import glob

# Create archive
with ZipFile("archive.zip", "w") as zf:
    for filename in glob.glob("*.txt"):
        zf.write(filename)

# Extract
with ZipFile("archive.zip", "r") as zf:
    zf.extractall("output_folder")
    print(zf.namelist())

Tips

  • Use compression=zipfile.ZIP_DEFLATED for actual compression; the default may store without compression.
  • writestr() allows adding content from memory without creating a temporary file.
  • Password-protected ZIPs are supported but rely on weak encryption; use pyzipper with AES for stronger security.

Common issues

  • Writing absolute paths into a ZIP can cause extraction issues; pass arcname to control the internal path.
  • Corrupted ZIP files raise zipfile.BadZipFile on open.
  • Large archives may require streaming extraction to avoid memory exhaustion.