Creating and Populating ZIP Files
Creating and Populating ZIP Files. So far, you’ve learned how to work with existing ZIP files. You’ve learned to read, write, and append member files to them by using different modes of
You’ve also learned how to read relevant metadata and how to extract the content of a given ZIP file. In this section of the course, you’ll code a few practical examples that will help you learn how to create ZIP files from several input files and from an entire directory using
zipfile and other Python tools.
You’ll also learn how to use
zipfile for file compression and more. Sometimes you need to create a ZIP archive from several related files. This way, you can have all the files in a single container for distributing them over a computer network or sharing with friends and colleagues.
for loop iterates over your list of input files and writes them into the underlying ZIP file using
.write(). Once the execution flow exits the
ZipFile automatically closes the archive, saving the changes for you.
Now you have a
multiple_files.zip archive containing all the files from your original list of files. Bundling the content of a directory into a single archive is another everyday use case for ZIP files.
Python has several tools that you can use with
ZipFile to approach this task. For example, you can use
pathlib to read the content of a given directory, and with that information, you can create a container archive using
Because the directory doesn’t contain subdirectories, you can use
pathlib.Path.iterdir() to iterate directly over its content. With this idea in mind, on-screen you’ll see how to build a ZIP file from the content of
Then the call to
.iterdir() returns an iterator over the entries in the underlying directory. Because you don’t have any subdirectories in
.iterdir() function yields only files. The
for loop iterates over the files and writes them into the archive. In this case, you pass
file_path.name to the second argument of
This argument is called
arcname and holds the name of the member file inside the resulting archive. All of the examples you’ve seen so far rely on the default value of
arcname, which is the same filename you passed as the first argument to
If you want to create a ZIP file with this same internal structure, then you need a tool that recursively iterates through the directory tree under
root_dir/. On-screen, you can see how to zip a complete directory tree like this one using
zipfile along with
Path.rglob() from the
Then you write every file and sub directory to the target ZIP archive. This time you use
Path.relative_to to get the relative path to each file, and then pass the result to the second argument of
.write(). This way, the resulting ZIP file ends up with the same internal structure as your original source directory. Again, you can get rid of this argument if you want your source directory to be at the root of your ZIP file.
Become a Member to join the conversation.