How to Create a Password Protected Zip Archive in Python
Generate a password-protected zip archive and verify password correctness using the standard library zipfile module.
Python code
47 linesimport zipfile
import tempfile
import os
def create_password_protected_zip(zip_path, password: str, files: dict):
"""
Create a zip archive with password protection (mock encryption).
Args:
zip_path: Path where the zip file will be created
password: Password for the archive
files: Dictionary mapping filenames to their content
"""
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
zf.setpassword(password.encode())
for name, content in files.items():
zf.writestr(name, content)
def try_extract(zip_path, password: str) -> bool:
"""Attempt to extract all files from a zip with a given password."""
try:
with zipfile.ZipFile(zip_path) as zf:
zf.setpassword(password.encode())
zf.extractall(path=tempfile.mkdtemp())
return True
except (RuntimeError, zipfile.BadZipFile):
return False
if __name__ == "__main__":
tmp_zip = "mock_secure.zip"
files = {"secret.txt": "This is hidden content.", "notes.txt": "Another secret."}
create_password_protected_zip(tmp_zip, "correct-horse", files)
# Demonstrate wrong password fails
wrong_attempt = try_extract(tmp_zip, "wrong-password")
print(f"Wrong password attempt: {wrong_attempt}")
# Demonstrate correct password succeeds
correct_attempt = try_extract(tmp_zip, "correct-horse")
print(f"Correct password attempt: {correct_attempt}")
# Clean up
os.remove(tmp_zip)
Output
Wrong password attempt: False
Correct password attempt: True
How it works
The zipfile module supports password protection by calling setpassword() before writing or extracting entries. When creating an archive, the password is encoded to bytes and applied to all files written via writestr(). During extraction, extractall() raises a RuntimeError for incorrect passwords, which the try_extract() function catches to return a boolean. This mock approach demonstrates the core pattern without relying on external encryption libraries.
Common mistakes
- Forgetting to encode the password with `.encode()` — zipfile expects bytes, not str.
- Applying `setpassword()` after writing files instead of before, leaving archives unprotected.
- Catching only `RuntimeError` but not `zipfile.BadZipFile` when handling corrupted archives.
Variations
- Use `pyminizip` for real AES-256 encryption instead of the weaker traditional zip encryption.
- Read the password from an environment variable or secrets manager instead of hardcoding it.
Real-world use cases
- Automating delivery of sensitive batch files to partners with per-client passwords.
- Creating encrypted backups of logs or configuration dumps in a scheduled cron job.
- Protecting exported reports before attaching them to automated email notifications.
Sponsored
More from Automation & scripting
- Aggregate Log Errors Count by Hour in Python easy
- Automate Tweeting New Blog Posts in Python easy
- Automatically Clean Temporary Files from Applications Using Python medium
- Automatically Download the Latest Software Release from GitHub with Python medium
- Automatically Generate Charts from CSV Files with One Command medium
- Automatically Generate Hardware Inventory Reports in Python easy
Keep learning
Related tutorials and quizzes for this topic.