import zipfile
import os
from getpass import getpass
def create_protected_zip(zip_filename, files_to_zip, password=None):
"""
Creates a password-protected ZIP file containing specified files.
Args:
zip_filename (str): Name of the output ZIP file
files_to_zip (list): List of file paths to include in the ZIP
password (str, optional): Password for the ZIP file. If None, prompts securely.
Returns:
bool: True if successful, False otherwise
"""
if not password:
password = getpass("Enter password for ZIP file: ")
confirm_password = getpass("Confirm password: ")
if password != confirm_password:
print("Passwords do not match!")
return False
try:
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
# Set password for the entire archive
zipf.setpassword(password.encode('utf-8'))
for file_path in files_to_zip:
if os.path.exists(file_path):
# Add file to ZIP with just its basename (no full path)
zipf.write(file_path, os.path.basename(file_path))
print(f"Added: {file_path}")
else:
print(f"Warning: File not found - {file_path}")
print(f"Successfully created protected ZIP: {zip_filename}")
return True
except Exception as e:
print(f"Error creating ZIP file: {e}")
return False
def extract_protected_zip(zip_filename, extract_to=".", password=None):
"""
Extracts a password-protected ZIP file.
Args:
zip_filename (str): Path to the ZIP file
extract_to (str): Directory to extract files to
password (str, optional): Password for the ZIP file. If None, prompts securely.
Returns:
bool: True if successful, False otherwise
"""
if not os.path.exists(zip_filename):
print(f"ZIP file not found: {zip_filename}")
return False
if not password:
password = getpass("Enter password to extract ZIP: ")
try:
with zipfile.ZipFile(zip_filename, 'r') as zipf:
zipf.setpassword(password.encode('utf-8'))
# Test the password by trying to read the file list
zipf.testzip()
# Extract all files
zipf.extractall(path=extract_to)
print(f"Successfully extracted to: {extract_to}")
return True
except RuntimeError as e:
if "Bad password" in str(e):
print("Incorrect password!")
else:
print(f"Error extracting ZIP: {e}")
return False
except Exception as e:
print(f"Error extracting ZIP: {e}")
return False
# Example usage
if __name__ == "__main__":
# Example: Create a protected ZIP
files = ["document.txt", "image.jpg"] # Replace with your actual files
zip_name = "protected_archive.zip"
# Uncomment to create a ZIP (you'll need to provide actual files)
# create_protected_zip(zip_name, files)
# Example: Extract a protected ZIP
# extract_protected_zip(zip_name)
This Python snippet provides two main functions for working with password-protected ZIP files:
create_protected_zip() - Creates a password-protected ZIP archive containing specified filesextract_protected_zip() - Extracts files from a password-protected ZIP archiveThe code securely handles password input using getpass, which prevents the password from being visible on the screen. It also validates that files exist before adding them to the archive and handles common errors like incorrect passwords.
protected_zip.pyfiles list in the example usage section to include actual file paths you want to archivepython protected_zip.pyTo create a protected ZIP file:
create_protected_zip() callTo extract a protected ZIP file:
extract_protected_zip() callNote: The password protection uses ZIP 2.0 encryption, which is suitable for general use but not for highly sensitive data. For stronger security, consider using specialized encryption tools.