Learn to create a zip or tar archive of a particular directory in python using two different methods with the help of illustrative examples.
You can also watch the following video presentation instead of reading this article.
Creating ZIP or TAR Archive in Python
Two different methods to create archives in Python are explained and illustrated below with the help of example code snippets. You can choose any one of the following as per your basic requirements and customizations required.
Method 1. Using
The easiest way to create a ZIP or TAR archive for a given directory containing any number of files and sub-directories is to use a Python Module named
You just have to follow the two given steps to create an archive with it.
- Import the
shutilmodule in your python code.
- Make use of its
make_archive()method to actually create the archive file.
make_archive() method takes three different arguments. The first argument has to be the name of the output archive file as a string, the second argument specifies whether you want to build a ZIP archive or TAR archive. And at last, the third argument specifies the path of the directory that you want to archive.
Example. Zipping a given folder or directory
In the following code snippet, we’re zipping a given directory named
Documents including all of its contents (files and sub-directories) using the
shutil.make_archive("Documents", 'zip', "Documents")
Note. In the first argument, while specifying the name of the archive file, you need not explicitly specify the extension like .zip with the name.
The above code creates a zip file in the current directory. I executed the above Python code on my Desktop directory and hence the zip file is also created on my desktop.
The output of the above code also specifies the full path of the created zip file.
Method 2. Using
In case you do not want to simply put all of the directory files in the archive and want to do the things like skipping some files and adding files to your archive following some conditions, then, you can make use of the
def zipdir(path, zipHandle):
for root, dirs, files in os.walk(path):
#Only Zip the files
#And Not the Sub-Directories
for file in files:
archiveFile = zipfile.ZipFile('Documents.zip', 'w', zipfile.ZIP_DEFLATED)
Running the above python code will loop through the Documents directory files one by one and will add them to the zip archive
Note. No sub-directories will be added to the archive using the above code.
Similarly, using the
tarfile module, you can also create TAR archives easily.
I hope you found this guide useful. If so, do share it with others who are willing to learn Python and other programming languages. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!