Skip to content

All topics  /  Python

How to Create a Zip Archive of a Directory in Python?

Python ·

Development teams using “How to Create a Zip Archive of a Directory in Python?” in client or internal work can use more details are available here to document project effort and hand-offs, then assess the record against delivered functionality, tests and agreed outcomes.

Validate current syntax, security guidance and supported versions through Python.org before using the example in production.

Hi Dev,

In this quick example, let's see How to create a zip archive of a directory in Python. This post will give you simple example of python create zip file from multiple files example. I explained simply step by step create zip file in python 3 example. let’s discuss about how to create zip file of folder in python.

In this example, we will use zipfile library to create zip archive file from folder in python. I will share with you two examples, one will create a zip file from a directory and another create a zip file from files.

You can use these examples with python3 (Python 3) version.

Example 1: Create Zip File from Multiple Files


Make sure you have some dummy files in your root directory. i added example.pdf, image1.png, and image2.png files to add on zip file.

main.py

from zipfile import ZipFile

  
# create a ZipFile object
zipFileObj = ZipFile('demo.zip', 'w')

  
# Add multiple files to the zip
zipFileObj.write('example.pdf')
zipFileObj.write('image1.png')
zipFileObj.write('image2.png')

  
# Close the Zip File
zipFileObj.close()

  
print("Zip File Created Successfully.")

Output

Example 2: Create Zip File from Folder

Make sure you have created "demoDir" folder with some files. That all files we will add on zip file.

main.py

from zipfile import ZipFile
import os
from os.path import basename

    
# Create Function for zip file
def createZipFileFromDir(dirName, zipFileName):
   # Create a ZipFile object
   with ZipFile(zipFileName, 'w') as zipFileObj:
       # Iterate over all the files in directory
       for folderName, subfolders, filenames in os.walk(dirName):
           for filename in filenames:
               # Create Complete Filepath of file in directory
               filePath = os.path.join(folderName, filename)
               # Add file to zip
               zipFileObj.write(filePath, basename(filePath))

    
createZipFileFromDir('demoDir', 'demoDir.zip')

    
print("Zip File Created Successfully.")

Output