Andromeda
Note

ZIP File Manipulation (Python)

Definition

The use of the zipfile module to create, read, and extract compressed archive files.

Why It Matters

Modern computing involves moving massive amounts of data. Zip automation is the key to efficient “Information Density.” It allows you to package complex projects into single, portable units, saving bandwidth and storage while ensuring that no file is left behind.

Core Concepts

  • ZipFile Object: Created with zipfile.ZipFile(path). Similar to the open() pattern for text files.
  • Modes: 'r' (read), 'w' (write/overwrite), 'a' (append).
  • Extraction:
    • .extractall(): Extracts all files into the current folder or a specified one.
    • .extract(file): Extracts a single file.
  • Compression: Use .write(filename, compress_type=zipfile.ZIP_DEFLATED) to add and compress files.
  • ZipInfo Objects: Contain metadata about individual files inside the ZIP (file size, compress size, etc.).
import zipfile

# Create a new ZIP file and add a file to it
with zipfile.ZipFile('new.zip', 'w') as new_zip:
    new_zip.write('spam.txt', compress_type=zipfile.ZIP_DEFLATED)

Connected Concepts