ItSolutionStuff.com

Python Create Zip Archive from Directory Example

By Hardik Savani • October 30, 2023
Python

Hi,

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.

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:

I hope it can help you...

Tags: Python
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Compare Two Dates in Python?

Read Now →

How to Check if Today is Monday or not in Python?

Read Now →

Python Check if Date is Weekend or Weekday Example

Read Now →

Python Subtract Seconds from DateTime Example

Read Now →

How to Add Seconds to DateTime in Python?

Read Now →

Python Subtract Minutes from DateTime Example

Read Now →

Python PATCH Request with Parameters Example

Read Now →

Python PUT Request with Parameters Example

Read Now →

Python POST Request with Parameters Example

Read Now →

Python GET Request with Parameters Example

Read Now →

Python Subtract Hours from Datetime Example

Read Now →