How to automatically zip your files with Python

People make use of zip files to store data on their computers and even transmit files over the Internet. Zipping data through different applications available out there, helps to pack a group of files into a single archive that takes less space than the originals.

Almost everyone who is reading this article had to zip files on their computer with the main purpose of sharing them via email, at least once in their own lives. Zipping files into archives is not rocket science. There are many free applications shared on the Internet that can help the user accomplish that.

Being a coder and passionate about discovering new ways of achieving computer tasks, I thought to give a try to available Python libraries to zip my files.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Although there are many ways to automatically zip files with the help of the Python computer programming language, this article will treat two of them.

The shutil.make_archive function

For those of you who are not aware of the Python’s builtin shutil module, according to the official documentation this module provides high level operations of files and collections of files. Operations include copying and removing files.

Based on my personal experience with the shutil module, it offers the function make_archive to create archive files such as zip or tar ones. As you may already know, before making use of the Python’s shutil.make_archive function you have to import it within your script or within your interactive session.

With the main purpose of following the code being shared through this article, create a new Python module called archive_code.py like shown below.

archive_code.py

Then open the above Python module in editing mode and make use of the Python’s builtin import statement like shown below to include the necessary tools within your session.

import shutil

Now that we have imported the main library, we can make use of any utility that comes with it. For example, the following code calls the make_archive function.

shutil.make_archive()

Once I managed to run the piece of Python code which is shown above, I got the following error.

Traceback (most recent call last):
File “”, line 1, in
TypeError: make_archive() takes at least 2 arguments (0 given)

As you can see from the above console output, the traceback is suggesting that the shutil.make_archive function takes at least two arguments. Given the fact that we did not provide any argument during the call, we got an error thrown on our interactive session.

According to the traceback printed above, the shutil.make_archive needs at least two arguments to run without errors. With the main purpose of breaking down high level stuff into little pieces, let’s test some stuff in the Python’s interactive console before writing code in the script which we have already created.

Run the following command on your Python’s interactive console.

shutil.make_archive(‘codetheory’, ‘zip’, ‘doesnotexist’)

Let’s explain the above piece of Python code. As you already know, the shutil.make_archive function creates an archive based on the format and files provided by the user. The first argument within the above Python command stands for the name of the archive which is going to be created; the second one for the format of the archive and the third one for the files to zip.

If you did run the above command, the following error was probably thrown into your Python interactive shell.

Traceback (most recent call last):
File “”, line 1, in
File “/usr/local/Cellar/python/2.7.12/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shutil.py”, line 536, in make_archive
os.chdir(root_dir)
OSError: [Errno 2] No such file or directory: ‘doenotexist’

As you can see from the above traceback printed on your interactive console, the function shutil.make_archive can not create a zip archive out of nothing; you must provide files that do exist in your own operating system.

The following piece of Python code creates a zip archive out of the directory christianity which is located on my Desktop.

shutil.make_archive(‘oltjano’, ‘zip’, ‘christianity’)

Once I managed to execute the piece of Python code being shown above, I got the following output on my interactive console.

‘/Users/oltjano/Desktop/oltjano.zip’

By doing a simple analysis on the value being returned by the function shutil.make_archive, we can easily come to the conclusion that it returns the absolute path of the archive which it creates.

With the main purpose of avoiding errors, make sure to provide the absolute path of the directory which you want to create an archive from. A better version of the Python code which we used above, is shown below.

shutil.make_archive(‘oltjano’, ‘zip’, ‘/Users/oltjano/Desktop/christianity’)

The archive being created should appear in the current working directory; in my case it appeared on my Desktop.

Now that you learned how to make use of the function shutil.make_archive to create a zip archive, it is time to learn a new way to archive the same task.

The zipfile.ZipFile class

According to the Python’s official documentation the zipfile.ZipFile class is responsible for reading and writing ZIP files. Let’s skip the words and get our hands dirty with a practical example.

Before going any further, make sure to restart your Python’s interactive shell and use the following code to import the required tools.

import zipfile

As you may already know, before we can make use of the tools that come within a builtin module, we must first import it with the help of the import statement like shown in the above piece of Python code.

Now let’s call the ZipFile class which is included in the module zipfile with the help of the code which is shown below.

zipfile.ZipFile()

Once I managed to run the Python code which is shown above, I got the following result displayed on my interactive console.

Traceback (most recent call last):
File “”, line 1, in
TypeError: __init__() takes at least 2 arguments (1 given)

As you can see, the __init__ of the class zipfile.ZipFile takes at least two arguments. Given the fact that we called it without any argument, an error was thrown.

The first argument which you most provide to the constructor of the class zipfile.ZipFile is the name of the archive; the second argument is the mode of operating the file. Are you going to write a ZIP file, or read an existing one?

Since the main purpose of this article is to teach people how to write ZIP archives, we have to open an archive in writing mode with the help of the Python code shown below.

zip_obj = zipfile.ZipFile(‘archive.zip’, ‘w’)

Based on my personal experience with the zipfile.ZipFile; the argument ‘w’ stands for writing mode. As you have already guessed the ‘archive.zip’ is the name of the archive which we are going to create.

Now that we have managed to open a ZIP archive in writing mode with the help of the Python’s zipfile.ZipFile, we can easily write files to it like shown below.

zip_obj.write(‘test.pdf’)

You can add as many files as you want to the ZIP archive by making use of the zipfile.ZipFile.write method. Once you are done writing files, make sure to close the ZIP archive the same way you close normal file objects in Python.

zip_obj.close()

You will end up with a ZIP archive in your working directory.

Final thoughts

We have already shown you how to write ZIP archives with the help of the Python computer programming language. Each one of the ways being taught through this article is a very effective one when it comes to automatically archiving files. Make sure to copy paste the code in the Python module which we created and call it based on your specific needs.

import shutil
from zipfile import ZipFile

# creates a ZIP archive based on a provided directory
shutil.make_archive('oltjano', 'zip', '/Users/oltjano/Desktop/christianity')

# writes specified files to a ZIP archive
zip_obj = zipfile.ZipFile('archive.zip', 'w')
zip_obj.write('test.pdf')
zip_obj.close()

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *

*