how to zip a folder

Folder Compression using Zip in Python

In this tutorial, we will learn how to compress a folder into a zip file using Python programming language. This can be useful when you want to save disk space or want to send multiple files as a single package.

Prerequisites

Before we start, make sure Python is installed on your computer. You can download and install the latest version of Python from the official website: https://www.python.org/downloads/

Step 1: Importing Required Modules

To compress a folder into a zip file, we need to import the shutil and zipfile modules.

python
import shutil
import zipfile

Step 2: Defining the Function

Next, we will define a function called zip_folder() that takes two parameters: the path of the folder to be compressed (source_folder) and the name of the output zip file (output_filename).

python
def zip_folder(source_folder, output_filename):
shutil.make_archive(output_filename, 'zip', source_folder)

Here, we use the make_archive() function provided by the shutil module to create a zip file. The function takes three parameters: the name of the output file (without the .zip extension), the type of the archive ('zip' in this case), and the source folder to be compressed.

Step 3: Calling the Function

Finally, we can call the zip_folder() function with the desired folder path and output file name.

python
zip_folder('/path/to/source_folder', 'output_file')

Make sure to replace '/path/to/source_folder' with the actual path of the folder you want to compress.

Conclusion

Congratulations! You have learned how to compress a folder into a zip file using Python. This can be a handy technique for various scenarios such as file backup, data transfer, or reducing file size. Experiment with different folders and filenames to explore further possibilities. Happy coding!