Python Create Zip Archive from Directory Example
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('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.")
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', 'demoDir.zip') print("Zip File Created Successfully.")
I hope it can help you...
We are Recommending you
- How to Compare Two Dates in Python?
- How to Check if Today is Monday or not in Python?
- Python Check if Date is Weekend or Weekday Example
- Python Subtract Seconds from DateTime Example
- How to Add Seconds to DateTime in Python?
- Python Subtract Minutes from DateTime Example
- Python PATCH Request with Parameters Example
- Python PUT Request with Parameters Example
- Python POST Request with Parameters Example
- Python GET Request with Parameters Example
- Python Subtract Hours from Datetime Example