zipfile | Python Standard Library – Real Python

The Python zipfile module provides tools to create, read, write, and extract ZIP archives. With just a few lines of code, you can manipulate ZIP files to back up data, share files, or save disk space.

Here’s a quick example:

Key Features

  • Creates ZIP archives
  • Reads and writes compressed files
  • Supports ZIP64 format for large files
  • Allows for extracting specific files from a ZIP archive
  • Provides a context manager for managing ZIP files
  • Supports multiple compression methods
  • Handles reading password-protected ZIP files
  • Allows adding files with custom archive names
  • Integrates with file-like objects or streams
  • Supports reading and writing metadata, including comments and timestamps
  • Enables appending files to existing archives

Frequently Used Classes and Functions

Examples

Reads the contents of a ZIP file:

Extracts all files from a ZIP archive:

Common Use Cases

  • Backing up directories and files to ZIP files
  • Inspecting the contents of third-party archives before extraction
  • Distributing Python projects as compressed archives
  • Manipulating ZIP files without extracting them to disk
  • Bundling datasets for reproducible experiments
  • Securely transmitting files by compressing and encrypting them

Real-World Example

Suppose you want to create a ZIP archive of all Python files in a project/ directory. This example demonstrates how to do that efficiently:

In this example, you create a ZIP archive containing all Python files in a directory, illustrating how the zipfile module can automate the archiving process efficiently.

Python's zipfile: Manipulate Your ZIP Files Efficiently

For additional information on related topics, take a look at the following resources: