When working with files in Python, you might often find yourself needing to compress multiple files into a single
archive. This can be useful for various purposes, such as reducing the size of data to send over a network or
simply organizing and storing files more efficiently.
In this blog post, we will discuss how to zip multiple files in Python using the built-in zipfile module.
Getting Started with the ZipFile Module
The zipfile module in Python allows you to work with Zip archives, providing functionalities to
read, write, and extract files from them. Let’s start by importing the module:
Zipping Multiple Files
To zip multiple files, you can follow these steps:
- Create a ZipFile object for writing.
- Add files to the archive using the write() method.
- Close the ZipFile object to finalize the archive.
Let’s dive into each step with an example: Assume we have three text files named file1.txt,
file2.txt, and file3.txt that we want to compress into a single archive called
1. Create a ZipFile Object for Writing
First, create a ZipFile object using the ZipFile() constructor with two arguments: the name of
the output archive and the mode in which you want to open the archive. Here, we’ll use the mode ‘w’ to open the
archive for writing:
with zipfile.ZipFile('output.zip', 'w') as zipf: # Add files to the archive here
This creates a new archive named output.zip and opens it in write mode. The with
statement ensures that the ZipFile object is properly closed after we’re done with it.
2. Add Files to the Archive
Now, you can add files to the archive using the write() method of the ZipFile object. Pass the
file path to the method, and it will add the file to the archive:
with zipfile.ZipFile('output.zip', 'w') as zipf: zipf.write('file1.txt') zipf.write('file2.txt') zipf.write('file3.txt')
This code adds the three text files to the output.zip archive.
3. Close the ZipFile Object
Finally, when you’re done adding files to the archive, simply close the ZipFile object by exiting the
with statement. This finalizes the archive, and you’ll now have a compressed output.zip
file containing your three text files:
with zipfile.ZipFile('output.zip', 'w') as zipf: zipf.write('file1.txt') zipf.write('file2.txt') zipf.write('file3.txt') # The ZipFile object is automatically closed here
In this blog post, we’ve learned how to zip multiple files in Python using the built-in zipfile
module. By following the three steps of creating a ZipFile object for writing, adding files to the archive, and
closing the object, you can easily create a compressed archive containing multiple files in Python. Don’t forget
to explore the zipfile module’s documentation for more advanced features and options!