In this tutorial, we will learn how to zip files using Python. Zipping files allows you to compress them, which helps in saving storage space and reduce the time taken to send files over the internet.
Python provides a built-in library called zipfile to work with zip files. We will explore this library and see how to compress and decompress zip files in Python.
Step 1: Import the zipfile library
Before working with zip files, we first need to import the zipfile library. We can do this using the following line of code:
1 |
import zipfile |
Step 2: Create a zip file
To create a zip file, we need to use the ZipFile class provided by the zipfile library. To create a zip file, we need to use it in the write mode (‘w’). We need to use the with statement to ensure that the zip file is closed after it’s written. Here’s an example:
1 2 |
with zipfile.ZipFile("output.zip", "w") as zipf: # Code to add files to the zip |
In this example, we are creating a zip file called output.zip in the write mode.
Step 3: Add files to the zip file
Once we have created a zip file, we can add files to it using the write() method of the ZipFile object.
Here’s an example of how to add a file called file.txt to our zip file:
1 2 3 |
file_to_zip = "file.txt" with zipfile.ZipFile("output.zip", "w") as zipf: zipf.write(file_to_zip, os.path.basename(file_to_zip)) |
In the above example, we use the os module to get the base name of the file being added to the zip file. This is necessary to avoid adding unnecessary folder paths to the zip. Don’t forget to import the os module at the beginning of your code:
1 |
import os |
Step 4: Zip multiple files
If you want to zip multiple files, simply loop through the list of files and use the write() method to add each file to the zip. Here’s an example:
1 2 3 4 |
files_to_zip = ["file1.txt", "file2.txt", "file3.txt"] with zipfile.ZipFile("output.zip", "w") as zipf: for file in files_to_zip: zipf.write(file, os.path.basename(file)) |
This code will create a zip file called output.zip containing the three files specified in the files_to_zip list.
Full code
1 2 3 4 5 6 7 8 |
import zipfile import os files_to_zip = ["file1.txt", "file2.txt", "file3.txt"] with zipfile.ZipFile("output.zip", "w") as zipf: for file in files_to_zip: zipf.write(file, os.path.basename(file)) |
In the given code example, we create a zip file called output.zip containing the three files specified in the files_to_zip list.
Conclusion
In this tutorial, we learned how to zip files using Python’s built-in zipfile library. We covered how to create a zip file, add files to it, and zip multiple files. This library makes it easy to compress and decompress zip files in Python, which is useful for saving storage space and reducing file transfer times.