Often Python developers need to work with zip files in Python. Zip files are commonly used by system administrators and software developers to compress many files and directories into a single zip file. It is great for archiving and compressing files, and saving space. You can compress and extract zip files without loss of data. They are easy to transfer as well as store. Generally, people compress and extract zip files using terminal commands. But sometimes, you may need to work with zip file in Python, in your website or web application. In this article, we will learn how to create, open, read, extract zip files. We will also learn how to add files to zip as well as get meta information about zip files.
Why Zip Files in Python
There are many use cases where you may need to work with zip files from within Python environment. For example, if you are developing a python-based website or application that allows users to upload one or more images/documents, then you will need to support zip files to improve upload speed and save space. After the zip file is uploaded to your website, you will need to extract it using a Python script. Therefore, you will need to use Python for zip files.
Another advantage is that if you use Python scripts to work with zip files, then it becomes platform independent, since you do not need to rely on local apps and tools for this purpose.
Zipfile Python Module
Python provides a powerful zipfile module that allows you to easily perform various tasks on zip files in Python. You can use it on Python console or call it from inside Python script. It allows you to create, read as well as extract zip files in Python. You can import the zipfile module using the following command.
import zipfile
In most cases, we will be using ZipFile class from this module. So you can also directly import this as shown.
from zipfile import ZipFile
How to Work With Zip Files in Python
Let us look at the different things you can do with zip files in Python.
How to Open Zip File in Python
How to Create Zip File in Python
One of the most common requirements for people is to create a zip file from a set of files and folders. For this, you can use write() function as shown below.
from zipfile import ZipFile
with ZipFile("./data.zip", "w") as zip:
zip.write('file1.txt')
zip.write('./projects')
In the above code, we have basically opened the target zip file in write mode. Then we have written individual file file1.txt and subfolder /projects into the zip file. For each instance, we have called write() function to add to the zip file.
If you want to add files in a folder to a zip, you may want to get a list of its files and subfolders and
from zipfile import ZipFile
file_paths=[]
directory='/home/ubuntu/projects'
for root, directories, files in os.walk(directory):
for filename in files:
filepath = os.path.join(root, filename)
file_paths.append(filepath)
with ZipFile("./data.zip", "w") as zip:
for file in file_paths:
zip.write(file)
In the above code, we first go through the names of files and subfolders of ‘/home/ubuntu/projects’ and store their full paths in a list. Then we loop through this list and add each of these files and folders, one by one, to the zip file.
How to Read Zip File Without Opening
Sometimes, you may want to just read the content of a single file without extracting it to the disk. Here is an example to read file test.txt in our zip file.
from zipfile import ZipFile
with zipfile.ZipFile("./data.zip") as zip:
with zip.open("data/assets/test.txt") as fp:
print(fp.read().decode())
In the above code, we open the zip file in read mode. Then we call open() function on this zip file handler. Lastly, we call read().decode() function.
How to Extract Zip File in Python
One of the most common requirements is to simply extract a zip file to a given location. You can do this by opening the file in read mode ‘r’ and calling extractall() function.
from zipfile import ZipFile
with ZipFile("./data.zip", "r") as zip:
zip.extractall()
The above code will extract all files and folders in zip file to current location.
Sometimes, you may have a large zip file with many content and you may want to extract only a single file from it. In such cases, you can use the extract() function. Here is an example to extract only the file named test.txt.
from zipfile import ZipFile
with ZipFile("./data.zip", "r") as zip:
zip.extract('test.txt')
Please note, this use case is different from reading the content of single file, mentioned earlier. In this case, the file is extracted to the disk. In the earlier case, the file’s contents are read without extracting it.
If your zip file is password protected then you will need to supply the password in extractall() function using its pwd argument.
from zipfile import ZipFile
with ZipFile("./data.zip", "r") as zip:
zip.extractall(pwd=bytes(<password>, 'utf-8'))
How to List Zip File Contents
Often you may need to view a zip file’s contents without extracting it. ZipFile module provides many functions to view a zip file’s contents without opening it. You can use listdir() function to view all the directories and files in a zip file in a tabular format.
from zipfile import ZipFile
with ZipFile("data.zip") as zip:
print(zip.printdir())
You will see table of output with file name, modified data and size.
File Name Modified Size
data/ 2025-04-24 19:00:16 0
data/assets/ 2025-04-24 19:00:24 20
data/assets/index.txt 2025-04-24 19:01:12 11
data/configurations.txt 2025-04-24 18:52:26 40
data/sample.txt 20255-04-24 18:52:16 0
Sometimes, you may want to get a list of directories and files in a zip file, as a list so that you can loop through them and do further processing. For this purpose, you can use namelist() function.
from zipfile import ZipFile
with zipfile.ZipFile("./data.zip") as zip:
print(zip.namelist()) # list of files and folders
You will see the following output list.
['data/', 'data/assets/', 'data/assets/index.txt', 'data/configurations.txt', 'data/sample.txt']
How to Add Files to Zip file
Sometimes, you may need to add just one or few files to an existing zip file, without disturbing its other contents. For this, you can use write() function available in ZipFile class.
from zipfile import ZipFile
with ZipFile("./data.zip", "a") as zip:
zip.write("sample.txt", arcname="project/sample.txt")
In the above code, we first open the zip file in append mode ‘a’. Please do not open the file in write mode, else the new file will completely overwrite the zip file’s existing contents instead of being appended to it.
We call write() function to append the file to zip. We specify the file name/path as first argument. By default, the file will be appended to the root location inside zip file. If you want to add it to another subfolder inside it, then use arcname argument and specify the file path inside zip file.
How to Get Information About Zip File
If you need to meta information about a zip file’s contents, that is, its files and directories then you can use infolist() function. It will return a list of objects where each object contains file name, size, compression type, etc.
from zipfile import ZipFile
with zipfile.ZipFile("./data.zip") as zip:
print(zip.infolist()) # list of files and folders
Here is the output you will see.
[<ZipInfo filename='data/' external_attr=0x10>, ...]
If you want to read the properties of the above displayed objects, then you can loop through them one by one to extract the information you need.
with ZipFile("./data.zip") as zip:
for file in zip.infolist():
print(file.filename)
print('\tModified:\t' + str(datetime.datetime(*file.date_time)))
print('\tSystem:\t\t' + str(file.create_system) + '(0 = Windows, 3 = Unix)')
print('\tZIP version:\t' + str(file.create_version))
print('\tCompressed:\t' + str(file.compress_size) + ' bytes')
print('\tUncompressed:\t' + str(file.file_size) + ' bytes')
In the above code, we loop through the result of infolist() function. In each iteration, we read some of the properties available in the object, such as filename, date_time, create_version, compress_size, file_size.
Conclusion
In this article, we have learnt many common use cases to work with zip files in Python. We have learnt how to create zip file, how to extract one or more files from a zip file. We have also learnt how to read a file without opening zip file, how to add a single file to zip file. Lastly, we learnt how to get the list of a zip file’s contents without extracting it, and how to get the meta information about each of its files and folders. You can use any of these solutions as per your requirement. Please note, it is always advisable to use context managers along with file handlers so that they are automatically closed after processing completes.
Also read:
How to Convert Pandas Dataframe into Dictionary
How to Convert Pandas Dataframe into List
How to Compare Two Lists in Python

Sreeram Sreenivasan is the Founder of Ubiq. He has helped many Fortune 500 companies in the areas of BI & software development.