zipfile
Updated March 13, 2026 · Modules
archives compression stdlib files zip
The zipfile module reads and writes ZIP archives. It supports both reading existing ZIP files and creating new ones, with optional compression. ZIP files are the standard archive format on Windows and widely used for distributing packaged software and bundled files.
Opening Archives
Reading an existing archive
Use ZipFile with mode ‘r’ to read an existing archive:
import zipfile
with zipfile.ZipFile('archive.zip', 'r') as zf:
print(zf.namelist())
# ['file1.txt', 'file2.txt', 'subdir/']
# Read a specific file
content = zf.read('file1.txt')
print(content)
Creating a new archive
Use mode ‘w’ to create a new archive:
import zipfile
with zipfile.ZipFile('new.zip', 'w') as zf:
# Add a file from disk
zf.write('source.txt', 'destination.txt')
# Add string content directly
zf.writestr('hello.txt', 'Hello, world!')
ZipFile Class
The ZipFile class is the primary interface for working with ZIP archives.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| file | str or Path or file-like | — | Path to the ZIP file or a file-like object |
| mode | str | ’r’ | Mode: ‘r’ read, ‘w’ create, ‘a’ append |
| compression | int | ZIP_STORED | Compression method: ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2, ZIP_LZMA |
| compresslevel | int | -1 | Compression level (1-9 for DEFLATED, 1-9 for BZIP2, 0-9 for LZMA) |
ZipFile Methods
| Method | Description |
|---|---|
| write() | Add a file to the archive |
| writestr() | Write data directly (string or bytes) |
| extractall() | Extract all files |
| extract() | Extract a single file |
| namelist() | List all file names |
| infolist() | List all ZipInfo objects |
| getinfo() | Get ZipInfo for a specific file |
| read() | Read file contents as bytes |
| close() | Close the archive |
ZipInfo Class
The ZipInfo class represents a single member in a ZIP archive.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| filename | str | — | Name of the file in the archive |
| date_time | tuple | (1980,1,1,0,0,0) | Modification time as (year, month, day, hour, minute, second) |
ZipInfo Attributes
| Attribute | Type | Description |
|---|---|---|
| filename | str | Name of the file in the archive |
| date_time | tuple | Modification time |
| compress_type | int | Compression method used |
| file_size | int | Uncompressed size in bytes |
| compress_size | int | Compressed size in bytes |
| CRC | int | CRC-32 checksum |
| external_attr | int | External file attributes |
Examples
Reading and extracting files
import zipfile
import os
with zipfile.ZipFile('data.zip', 'r') as zf:
# List all files
for name in zf.namelist():
info = zf.getinfo(name)
print(f"{name}: {info.file_size} bytes")
# Extract everything
zf.extractall('output_dir')
# Extract a specific file
zf.extract('specific.txt', 'output_dir')
Creating a compressed archive
import zipfile
with zipfile.ZipFile('backup.zip', 'w', zipfile.ZIP_DEFLATED) as zf:
# Add multiple files
for filename in ['file1.txt', 'file2.txt', 'file3.txt']:
zf.write(filename)
# Add with custom ZipInfo
info = zipfile.ZipInfo('custom.txt')
info.date_time = (2024, 1, 15, 10, 30, 0)
zf.writestr(info, 'Content with custom metadata')
Common Patterns
List contents with details
import zipfile
from datetime import datetime
with zipfile.ZipFile('archive.zip', 'r') as zf:
for info in zf.infolist():
dt = datetime(*info.date_time)
print(f"{info.filename:30} {info.file_size:>8} {dt}")
Selective extraction
import zipfile
with zipfile.ZipFile('archive.zip', 'r') as zf:
# Extract only .txt files
for member in zf.namelist():
if member.endswith('.txt'):
zf.extract(member, 'text_files/')
Create archive from directory
import zipfile
import os
def zip_directory(source_dir, output_path):
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zf:
for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, source_dir)
zf.write(file_path, arcname)
Errors
Common exceptions
| Exception | When it occurs |
|---|---|
| BadZipFile | File is not a valid ZIP archive or is corrupted |
| LargeZipFile | ZIP file exceeds 2GB (use ZIP64 format) |
| PasswordRequired | Attempting to read an encrypted archive without password |
| ZipShortRead | Unexpected end of file while reading |