Last modified: Feb 10, 2026 By Alexander Williams
Python Zip Folder: Compress Directories
Working with files is a common task in programming.
You often need to bundle multiple files together. The ZIP format is perfect for this.
It reduces file size and keeps related files organized. Python makes this process simple.
This article will show you how to zip entire folders in Python.
We will use the built-in zipfile module. You will learn to create, read, and extract ZIP archives.
Why Zip Folders in Python?
Zipping folders has many practical uses. It saves disk space by compressing files.
It also makes file transfer faster over networks. Bundling files into one archive simplifies management.
Python scripts can automate this process. This is useful for backups, data distribution, or application deployment.
Understanding how to use the zipfile module is a valuable skill. It is different from the zip() function used for iterating over lists.
For that, you can read our guide on the Python Zip Function Guide: Iterate in Parallel.
Getting Started with the Zipfile Module
Python includes the zipfile module in its standard library. You do not need to install anything extra.
Start by importing it into your script. This module provides tools to create, read, and modify ZIP files.
Its main class is ZipFile. You use this class to work with archive files.
Let's look at the basic steps to create a ZIP file from a folder.
Importing the Module
First, import the necessary module. You will also use the os module to navigate directories.
import zipfile
import os
How to Zip an Entire Folder
To compress a folder, you need to walk through its directory tree. You add each file to the archive.
The os.walk() function is perfect for this. It generates file names in a directory tree.
You then use the write() method of a ZipFile object. Let's see a complete example.
def zip_folder(folder_path, output_path):
"""
Compresses an entire folder into a ZIP file.
Args:
folder_path (str): Path to the folder to zip.
output_path (str): Path for the output ZIP file.
"""
# Create a ZipFile object in write mode
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
# Walk through the directory
for root, dirs, files in os.walk(folder_path):
for file in files:
# Create the full file path
file_path = os.path.join(root, file)
# Create the archive name (relative path inside the zip)
# This removes the original folder path from the archive path
arcname = os.path.relpath(file_path, os.path.dirname(folder_path))
# Add the file to the zip
zipf.write(file_path, arcname)
print(f"Added: {arcname}")
# Example usage
source_folder = "./my_project"
output_zip = "./my_project_backup.zip"
zip_folder(source_folder, output_zip)
print("Folder zipped successfully!")
This function takes a folder path and an output ZIP file path. It uses a context manager (with statement).
This ensures the ZIP file is closed properly. The ZIP_DEFLATED argument enables compression.
The os.walk() loop finds every file. The arcname variable stores the file's relative path inside the archive.
This keeps the folder structure intact. The write() method does the actual adding.
Understanding the Output
When you run the script, it prints each file added. The final message confirms success.
You will have a new file named my_project_backup.zip. It contains all files from my_project.
The structure inside the ZIP will match the original folder.
Added: my_project/main.py
Added: my_project/utils/helper.py
Added: my_project/data/config.json
Folder zipped successfully!
Extracting a Zipped Folder
Creating a ZIP is only half the job. You also need to extract files.
The zipfile module makes extraction easy. Use the extractall() method.
For more details on reading and extracting, see our article on Python Zip Files: Create, Read, Extract Archives.
def extract_zip(zip_path, extract_to):
"""
Extracts all contents of a ZIP file to a specified directory.
Args:
zip_path (str): Path to the ZIP file.
extract_to (str): Directory to extract files into.
"""
# Ensure the extraction directory exists
os.makedirs(extract_to, exist_ok=True)
# Open the zip file in read mode and extract all
with zipfile.ZipFile(zip_path, 'r') as zipf:
zipf.extractall(extract_to)
print(f"Extracted to: {extract_to}")
# Example usage
extract_zip("./my_project_backup.zip", "./extracted_project")
The extractall() method is straightforward. It takes a target directory path.
The exist_ok=True argument prevents errors if the folder already exists.
All files and subdirectories are recreated in the target location.
Advanced Techniques and Best Practices
You can customize the zipping process. Let's explore some useful options.
Compression Level
The ZIP_DEFLATED method supports compression levels. You can set it when creating the ZipFile object.
However, the standard zipfile module uses a default level. For more control, you might need other libraries.
Zipping Specific File Types
You might want to zip only certain files. For example, only .py or .txt files.
You can add a filter inside the loop. Check the file extension before adding it.
def zip_only_py_files(folder_path, output_path):
"""Zips only Python (.py) files from a folder."""
with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.py'): # Filter for Python files
file_path = os.path.join(root, file)
arcname = os.path.relpath(file_path, os.path.dirname(folder_path))
zipf.write(file_path, arcname)
Handling Large Folders
Zipping a very large folder can use a lot of memory. The zipfile module processes files one by one.
This is generally memory-efficient. However, for massive archives, consider splitting the ZIP into parts.
You can also add progress indicators for long operations.
Common Errors and Solutions
You might encounter some errors while zipping folders. Here are common ones and how to fix them.
FileNotFoundError
This happens if the source folder path is wrong. Always check if the path exists before zipping.
Use os.path.exists(folder_path) to validate.
PermissionError
You may not have read permission for some files. Or write permission for the output location.
Run your script with appropriate permissions. On Linux/macOS, you might need sudo.
Large File Error (ZIP64)
ZIP files over 4 GB require the ZIP64 extension. The zipfile module supports it automatically.
Ensure you are using a recent Python version. It handles large files seamlessly.
Conclusion
Zipping folders in Python is a powerful and straightforward task. The built-in zipfile module provides all necessary tools.
You learned how to compress an entire directory. You also learned how to extract its contents.
Remember to use the with statement for safe file handling. This prevents resource leaks.
Automating file compression saves time and reduces errors. You can integrate this into your backup scripts or data pipelines.
For related operations on single files, check out our tutorial on Python Zip Directory: Compress Files Easily.
Start experimenting with the zipfile module today. It is an essential tool for any Python developer working with files.