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
- Open a
ZipFilein write mode (w) or append mode (a). - Add files with
.write()or.writestr(). - 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_DEFLATEDfor 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
pyzipperwith AES for stronger security.
Common issues
- Writing absolute paths into a ZIP can cause extraction issues; pass
arcnameto control the internal path. - Corrupted ZIP files raise
zipfile.BadZipFileon open. - Large archives may require streaming extraction to avoid memory exhaustion.