How to Create Zip Archive from Directory in Python?

Hi Guys,
This article goes in detailed on python create zip file from directory. if you have question about how to create zip file of folder in python then I will give simple example with solution. I explained simply about python zip files from directory. let’s discuss about python create zip file from multiple files example. Let's see bellow example create zip file in python 3 example.
In this example, we'll show you how to build a zip archive file from a folder in Python using the zipfile package. I'll give you two examples, one of which will produce a zip file from files and the other from a directory.
You can use these examples with python3 (Python 3) version.
So let's see bellow example:
Example 1: Create Zip File from Multiple Files
Make sure your root directory has a few dummy files. I added an instance. add the files example1.png, and example.png to the zip file.
main.pyfrom zipfile import ZipFile # create a ZipFile object zipFileObj = ZipFile('demo.zip', 'w') # Add multiple files to the zip zipFileObj.write('example.png') zipFileObj.write('example1.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 "demo" folder with some files. That all files we will add on zip file.
main.pyfrom 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('demo', 'demoDir.zip') print("Zip File Created Successfully.")Output

It will help you....
Happy Pythonic Coding!