by BehindJava

How to Unzip and Zip Files in Python with examples

Home » python » How to Unzip and Zip Files in Python with examples

In this tutorial we are going to learn about Unzipping and Zipping Files in Python with examples.

As you are probably aware, files can be compressed to a zip format. Often people use special programs on their computer to unzip these files, luckily for us, Python can do the same task with just a few simple lines of code.

Create Files to Compress

# slashes may need to change for MacOS or Linux
f = open("new_file.txt",'w+')
f.write("Here is some text")
# slashes may need to change for MacOS or Linux
f = open("new_file2.txt",'w+')
f.write("Here is some text")

Zipping Files

The zipfile library is built in to Python, we can use it to compress folders or files. To compress all files in a folder, just use the os.walk() method to iterate this process for all the files in a directory.

import zipfile
Create Zip file first , then write to it (the write step compresses the files.)
comp_file = zipfile.ZipFile('','w')

Extracting from Zip Files

We can easily extract files with either the extractall() method to get all the files, or just using the extract() method to only grab individual files.

zip_obj = zipfile.ZipFile('','r')

Using shutil library

Often you don’t want to extract or archive individual files from a .zip, but instead archive everything at once. The shutil library that is built in to python has easy to use commands for this:

import shutil
The shutil library can accept a format parameter, format is the archive format: one of "zip", "tar", "gztar", "bztar", or "xztar".
'C:\\Users\\Marcial\\Pierian-Data-Courses\\Complete-Python-3-Bootcamp\\12-Advanced Python Modules'
directory_to_zip='C:\\Users\\Marcial\\Pierian-Data-Courses\\Complete-Python-3-Bootcamp\\12-Advanced Python Modules'
# Creating a zip archive
output_filename = 'example'
# Just fill in the output_filename and the directory to zip
# Note this won't run as is because the variable are undefined
'C:\\Users\\Marcial\\Pierian-Data-Courses\\Complete-Python-3-Bootcamp\\12-Advanced Python Modules\\'
# Extracting a zip archive
# Notice how the parameter/argument order is slightly different here