Python Create Zip Archive from Directory Example

By Hardik Savani October 30, 2023 Category : Python


This example is focused on python create zip archive from directory. I explained simply about python create zip file from directory. you'll learn how to create zip file of folder in python. this example will help you python zip files from directory.

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.

from zipfile import ZipFile
# create a ZipFile object
zipFileObj = ZipFile('', 'w')
# Add multiple files to the zip
# Close the Zip File
print("Zip File Created Successfully.")


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.

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', '')
print("Zip File Created Successfully.")


I hope it can help you...

Tags :