Skip to main content Brad's PyNotes

Zipfile Module

TL;DR

The zipfile module provides tools for creating, reading, and extracting ZIP archives with support for multiple compression methods and password protection.

Interesting!

The module supports ZIP64 extensions, allowing you to work with ZIP files larger than 4GB and containing more than 65,535 files - breaking traditional ZIP format limits!

Creating ZIP Archives

python code snippet start

from zipfile import ZipFile

# Create a new ZIP file
with ZipFile('my_archive.zip', 'w') as zipf:
    zipf.write('document.txt')
    zipf.write('image.png')
    zipf.writestr('hello.txt', 'Hello, World!')

python code snippet end

Reading ZIP Contents

python code snippet start

with ZipFile('my_archive.zip', 'r') as zipf:
    # List all files
    print(zipf.namelist())
    
    # Read a specific file
    with zipf.open('hello.txt') as f:
        content = f.read().decode('utf-8')
        print(content)

python code snippet end

Extracting Files

python code snippet start

with ZipFile('my_archive.zip', 'r') as zipf:
    # Extract all files
    zipf.extractall('destination/')
    
    # Extract specific file
    zipf.extract('document.txt', 'specific/path/')

python code snippet end

Compression Methods

python code snippet start

from zipfile import ZipFile, ZIP_DEFLATED, ZIP_BZIP2

with ZipFile('compressed.zip', 'w', compression=ZIP_DEFLATED) as zipf:
    zipf.write('large_file.txt')

python code snippet end

The zipfile module makes archive management straightforward while handling complex ZIP format details behind the scenes. Use zipfile with pathlib for file management and glob for batch operations . For secure file handling, combine with temporary directories and gzip compression for different compression needs.

Reference: zipfile — Work with ZIP archives