Python provides built-in support for handling ZIP files using the zipfile
module. ZIP files allow multiple files to be compressed into a single archive, reducing file size and simplifying file transfers.
Why Use ZIP Files?
- Reduces file size (compression).
- Groups multiple files together for easy sharing.
- Supports password protection (with third-party libraries).
- Extracts files without modifying the originals.
1. Importing the zipfile
Module
To work with ZIP files, first import the zipfile
module:
import zipfile
2. Creating a ZIP File (write
mode)
Use zipfile.ZipFile()
in write mode ("w"
) to create a ZIP file and add files to it.
Example: Creating a ZIP File
import zipfile
# Create a ZIP file and add files
with zipfile.ZipFile("my_archive.zip", "w") as zipf:
zipf.write("file1.txt") # Add file1.txt to the ZIP
zipf.write("file2.txt") # Add file2.txt to the ZIP
print("ZIP file created successfully!")
The "w"
mode overwrites an existing ZIP file. Use "a"
to append.
3. Adding Files to an Existing ZIP (append
mode)
with zipfile.ZipFile("my_archive.zip", "a") as zipf:
zipf.write("new_file.txt") # Add new_file.txt
print("File added to ZIP successfully!")
Use "a"
mode to append files without overwriting the ZIP file.
4. Creating a ZIP File with Compression
To reduce file size, use ZIP_DEFLATED
compression.
with zipfile.ZipFile("compressed.zip", "w", zipfile.ZIP_DEFLATED) as zipf:
zipf.write("file1.txt")
zipf.write("file2.txt")
print("Compressed ZIP file created!")
Compression reduces file size but takes extra processing time.
5. Extracting Files from a ZIP
Extract a Single File
with zipfile.ZipFile("my_archive.zip", "r") as zipf:
zipf.extract("file1.txt", "output_folder") # Extract to output_folder
print("File extracted successfully!")
Extract All Files
with zipfile.ZipFile("my_archive.zip", "r") as zipf:
zipf.extractall("output_folder") # Extract all files to output_folder
print("All files extracted successfully!")
Always specify an output folder to avoid cluttering the working directory.
6. Listing Files Inside a ZIP
with zipfile.ZipFile("my_archive.zip", "r") as zipf:
print(zipf.namelist()) # List of files inside ZIP
Use namelist()
to get a list of archived files.
7. Checking File Information Inside a ZIP
with zipfile.ZipFile("my_archive.zip", "r") as zipf:
for file_info in zipf.infolist():
print(f"Filename: {file_info.filename}, Size: {file_info.file_size} bytes")
Use infolist()
to get details like file size and modification date.
8. Checking if a File Exists in a ZIP
with zipfile.ZipFile("my_archive.zip", "r") as zipf:
if "file1.txt" in zipf.namelist():
print("file1.txt exists in the ZIP!")
Useful for verifying the presence of specific files.
9. Deleting a File from a ZIP (Workaround)
The zipfile
module does not support direct deletion of files. To remove a file, create a new ZIP without the unwanted file.
import zipfile
# Create a new ZIP without "file1.txt"
with zipfile.ZipFile("my_archive.zip", "r") as zipf:
files = [f for f in zipf.namelist() if f != "file1.txt"]
with zipfile.ZipFile("new_archive.zip", "w") as new_zip:
for file in files:
new_zip.write(file)
print("File removed from ZIP!")
Creates a new ZIP without the unwanted file.
10. Password-Protecting a ZIP File (Using pyzipper
)
The zipfile
module does not support password-protected ZIPs, but the pyzipper
library does.
import pyzipper
with pyzipper.AESZipFile("secure.zip", "w", compression=pyzipper.ZIP_DEFLATED, encryption=pyzipper.WZ_AES) as zipf:
zipf.setpassword(b"mypassword") # Set password (must be bytes)
zipf.write("file1.txt")
print("Password-protected ZIP created!")
Install pyzipper
:
pip install pyzipper
11. Extracting a Password-Protected ZIP (pyzipper
)
import pyzipper
with pyzipper.AESZipFile("secure.zip", "r") as zipf:
zipf.setpassword(b"mypassword") # Provide the password
zipf.extractall("output_folder")
print("Password-protected ZIP extracted!")
Password must be provided as bytes (b"mypassword"
).
12. Handling ZIP File Errors (try-except
)
To avoid crashes, use exception handling.
import zipfile
try:
with zipfile.ZipFile("my_archive.zip", "r") as zipf:
zipf.extractall("output_folder")
except FileNotFoundError:
print("Error: ZIP file not found!")
except zipfile.BadZipFile:
print("Error: Invalid ZIP file!")
Common Errors:
FileNotFoundError
– ZIP file is missing.zipfile.BadZipFile
– Corrupt or invalid ZIP file.
13. Summary Table
Operation | Method | Example |
---|---|---|
Create a ZIP file | zipfile.ZipFile("file.zip", "w") | zipf.write("file.txt") |
Append to ZIP file | zipfile.ZipFile("file.zip", "a") | zipf.write("new_file.txt") |
Extract a single file | extract("file.txt") | zipf.extract("file.txt", "folder") |
Extract all files | extractall("folder") | zipf.extractall("folder") |
List ZIP contents | namelist() | zipf.namelist() |
Check file info | infolist() | zipf.infolist() |
Check if file exists | "file.txt" in zipf.namelist() | if "file.txt" in zipf.namelist(): |
Delete a file | Create new ZIP without file | Workaround method |
Password protect ZIP | pyzipper.AESZipFile() | zipf.setpassword(b"mypassword") |
Handle errors | try-except | except zipfile.BadZipFile: |