📦 Zipping and Unzipping Files with Python
When working with multiple files or large datasets, compressing files into zip archives and later extracting them is a common task. Python makes this super easy using built-in modules like zipfile
.
In this tutorial, we'll cover:
✅ Zipping files and directories
✅ Unzipping and extracting content
✅ Working with password-protected zip files
✅ Real-world use cases
🧰 What You’ll Need
-
Python 3.x
-
Basic file handling skills
-
Some zip files to work with
📂 Zipping Files and Directories
To create a zip archive of a file or folder, we’ll use Python’s zipfile
module.
1. Zipping a Single File
import zipfile
def zip_file(file_name, zip_name):
with zipfile.ZipFile(zip_name, 'w') as zipf:
zipf.write(file_name, arcname=file_name.split('/')[-1])
print(f"✅ {file_name} has been zipped as {zip_name}")
# Usage
zip_file('example.txt', 'example.zip')
-
'w'
mode is for writing a new zip archive. -
arcname
allows renaming the file within the archive.
2. Zipping Multiple Files
def zip_multiple_files(file_names, zip_name):
with zipfile.ZipFile(zip_name, 'w') as zipf:
for file in file_names:
zipf.write(file, arcname=file.split('/')[-1])
print(f"✅ {zip_name} has been created with files: {', '.join(file_names)}")
# Usage
files = ['file1.txt', 'file2.txt', 'file3.txt']
zip_multiple_files(files, 'multiple_files.zip')
3. Zipping an Entire Directory
You can zip an entire folder and its contents using os.walk()
to loop through the directory.
import os
def zip_directory(directory_name, zip_name):
with zipfile.ZipFile(zip_name, 'w') as zipf:
for foldername, subfolders, filenames in os.walk(directory_name):
for filename in filenames:
file_path = os.path.join(foldername, filename)
arcname = os.path.relpath(file_path, directory_name)
zipf.write(file_path, arcname)
print(f"✅ {directory_name} has been zipped as {zip_name}")
# Usage
zip_directory('my_folder', 'my_folder.zip')
📥 Unzipping Files
To extract files from a zip archive, we can also use the zipfile
module.
1. Extract All Files from a Zip Archive
def unzip_file(zip_name, extract_to):
with zipfile.ZipFile(zip_name, 'r') as zipf:
zipf.extractall(extract_to)
print(f"✅ All files from {zip_name} have been extracted to {extract_to}")
# Usage
unzip_file('example.zip', './extracted_files')
2. Extract a Specific File from a Zip Archive
def unzip_single_file(zip_name, file_name, extract_to):
with zipfile.ZipFile(zip_name, 'r') as zipf:
zipf.extract(file_name, extract_to)
print(f"✅ {file_name} has been extracted to {extract_to}")
# Usage
unzip_single_file('example.zip', 'file1.txt', './extracted_files')
3. List All Files in a Zip Archive
def list_files_in_zip(zip_name):
with zipfile.ZipFile(zip_name, 'r') as zipf:
files = zipf.namelist()
print(f"Files in {zip_name}: {files}")
# Usage
list_files_in_zip('example.zip')
🔒 Handling Password-Protected Zip Files
To handle password-protected zip files, we can use pyzipper
, a third-party package, as the zipfile
module doesn't support encrypted archives.
Install pyzipper
:
pip install pyzipper
1. Zipping with Password Protection
import pyzipper
def zip_with_password(file_name, zip_name, password):
with pyzipper.AESZipFile(zip_name, 'w') as zipf:
zipf.setpassword(password.encode())
zipf.write(file_name, arcname=file_name.split('/')[-1])
print(f"✅ {file_name} has been zipped with password protection as {zip_name}")
# Usage
zip_with_password('secret_file.txt', 'protected.zip', 'my_secret_password')
2. Unzipping a Password-Protected File
def unzip_with_password(zip_name, password, extract_to):
with pyzipper.AESZipFile(zip_name, 'r') as zipf:
zipf.setpassword(password.encode())
zipf.extractall(extract_to)
print(f"✅ Files from {zip_name} have been extracted to {extract_to}")
# Usage
unzip_with_password('protected.zip', 'my_secret_password', './extracted_files')
🔄 Additional Useful Tips
-
Check if File is a Zip: You can use
zipfile.is_zipfile()
to verify if a file is a valid zip archive.if zipfile.is_zipfile('example.zip'): print("✅ It's a valid zip file.") else: print("❌ Invalid zip file.")
-
Zip File Compression: You can control the compression level with
zipfile.ZIP_DEFLATED
(default) orzipfile.ZIP_BZIP2
andzipfile.ZIP_LZMA
for higher compression ratios.with zipfile.ZipFile('compressed.zip', 'w', zipfile.ZIP_LZMA) as zipf: zipf.write('large_file.txt')
💡 Real-World Use Cases
Use Case | Description |
---|---|
📊 Data Storage | Compress large datasets for storage or email delivery |
🧰 Backup System | Automate backup of files and directories |
🖼️ Image Processing | Zip and email image files for processing |
🚚 Sending Multiple Files | Compress logs or multiple reports into a single zip archive for easier sharing |
🧠Final Thoughts
Python makes file compression and extraction extremely simple using the built-in zipfile
module and the pyzipper
library for password protection. These capabilities are invaluable when managing backups, packaging files for delivery, or automating the compression of large datasets.
By zipping and unzipping files with Python, you can reduce storage size, improve file transfer speed, and create automated workflows for file handling.