
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Zip a Folder Recursively Using Python
Zipping a folder recursively means compressing a folder along with all its subfolders and files. In this article, we will explore all the possible ways to zip a folder recursively using Python.
Using zipfile and os.walk()
In Python, we have the methods zipfile() and os.walk() to zip all the folders recursively. This is a manual approach of zipping the available subfolders and files into one. Following is an example that shows how to zip a folder recursively using Python -
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) # Usage zip_folder_manual('my_folder', 'my_folder.zip')
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 useful when we want to zip an entire directory with minimal code.
Below is an example that uses the shutil.make_archive() method to zip a folder using Python -
import shutil # Folder to archive source_dir = 'my_project' # Create my_project.zip in the current directory shutil.make_archive('my_project', 'zip', source_dir) print("Folder zipped successfully.")
Below is the output of the above program -
Folder zipped successfully.