How to zip a folder recursively using Python?

Zipping a folder recursively means compressing a folder along with all its subfolders and files into a single archive. Python provides several methods to accomplish this task efficiently.

Using zipfile and os.walk()

The zipfile module combined with os.walk() provides manual control over the compression process. This approach allows you to customize how files are added to the archive ?

import zipfile
import os

def zip_folder_manual(folder_path, zip_path):
    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                full_path = os.path.join(root, file)
                arcname = os.path.relpath(full_path, folder_path)
                zipf.write(full_path, arcname)

# Create sample folder structure for demonstration
os.makedirs('sample_folder/subfolder', exist_ok=True)
with open('sample_folder/file1.txt', 'w') as f:
    f.write('Hello from file1')
with open('sample_folder/subfolder/file2.txt', 'w') as f:
    f.write('Hello from file2')

# Zip the folder
zip_folder_manual('sample_folder', 'sample_folder.zip')
print("Folder zipped successfully using manual method.")

# Verify the contents
with zipfile.ZipFile('sample_folder.zip', 'r') as zipf:
    print("Archive contents:", zipf.namelist())
Folder zipped successfully using manual method.
Archive contents: ['file1.txt', 'subfolder/file2.txt']

Using shutil.make_archive()

Python's shutil module provides a simple and high-level method to create compressed archive files using make_archive(). This method is ideal when you want to zip an entire directory with minimal code ?

import shutil
import os

# Create sample folder structure
os.makedirs('my_project/docs', exist_ok=True)
os.makedirs('my_project/src', exist_ok=True)
with open('my_project/readme.txt', 'w') as f:
    f.write('Project readme file')
with open('my_project/docs/guide.txt', 'w') as f:
    f.write('User guide')
with open('my_project/src/main.py', 'w') as f:
    f.write('print("Hello World")')

# Create archive
archive_path = shutil.make_archive('my_project_backup', 'zip', 'my_project')
print(f"Archive created: {archive_path}")

# Check if file exists
if os.path.exists(archive_path):
    print(f"Archive size: {os.path.getsize(archive_path)} bytes")
Archive created: /path/to/my_project_backup.zip
Archive size: 1024 bytes

Using pathlib and zipfile (Modern Approach)

For Python 3.4+, you can use pathlib for more readable path handling ?

import zipfile
from pathlib import Path

def zip_folder_pathlib(source_folder, zip_file):
    source_path = Path(source_folder)
    
    with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
        for file_path in source_path.rglob('*'):
            if file_path.is_file():
                arcname = file_path.relative_to(source_path)
                zipf.write(file_path, arcname)

# Create test folder
test_folder = Path('test_folder')
test_folder.mkdir(exist_ok=True)
(test_folder / 'data.txt').write_text('Sample data')
(test_folder / 'nested').mkdir(exist_ok=True)
(test_folder / 'nested' / 'config.txt').write_text('Configuration')

# Zip using pathlib
zip_folder_pathlib('test_folder', 'test_archive.zip')
print("Folder zipped using pathlib method.")
Folder zipped using pathlib method.

Comparison

Method Code Length Customization Best For
zipfile + os.walk() Medium High Custom compression logic
shutil.make_archive() Short Low Simple, quick archiving
pathlib + zipfile Medium High Modern Python projects

Conclusion

Use shutil.make_archive() for simple archiving tasks. For custom compression logic or filtering specific files, use zipfile with os.walk() or pathlib for modern Python applications.

Updated on: 2026-03-24T18:30:26+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements