How to Zip and Unzip Files in Python: A Step-by-Step Guide

Learn how to zip and unzip files in Python with our step-by-step guide. Explore Python's zipfile module, compression techniques, and practical examples
E
Edtoks1:54 min read

Zipping files

files can be zipped and unzipped using zipfile the module For this exercise create two files test1.txt and test2.txt using below Python code.

file1 = open('test1.txt', 'w')
file1.write('This is test file one')
file1.close()
file2 = open('test2.txt', 'w')
file2.write('This is test file two')
file2.close()

Now execute the below python code to create a zip file. Check each comment line in the code. 

import zipfile

# Create a Zip file
cf = zipfile.ZipFile('cf.zip', 'w')
# Now add the files to cf file
cf.write('test1.txt', compress_type=zipfile.ZIP_DEFLATED)
cf.write('test2.txt', compress_type=zipfile.ZIP_DEFLATED)
#Now close zip file
cf.close()

 

Verify the output with ls -ltr cf.zip

extracted zipped file

Now extract actual files from the zip file. Execute below code

import zipfile

# Open a Zip file to read
cf = zipfile.ZipFile('cf.zip', 'r')
# Now extract the files, pass the directiry to which files has to be written
cf.extractall('actualFiles')
cf.close()
You can verify with ls -ltr actualFiles

Zipping a directory.

To zip directory better use shutil module.

import shutil
directory = '/Users/xxxxxx/pythontest/actualFiles'
output = 'compressDir'
shutil.make_archive(output, 'zip', directory)

Output is

/Users/xxxxxx/pythontest/compressDir.zip

 

extract zipped directory.

import shutil
shutil.unpack_archive('compressDir.zip', 'unzippedDir', 'zip')

 

You can verify with ls -ltr unzippedDir

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.