How to Zip Directory using Python? – Archive folder

Archive or Zip all files in Directory

The code in this page will Zip directory full of files. It will first get folder path as input. Then loop thru the directory & its sub-directories to get all the files list.

Then each file in the list is added to the Zip archive. It will also preserve the path of each file.

Here is one of the method in Python to compress the directory.

#-Import Zipfiel Library
import os #-To get path variables
import zipfile

#-Define zip file to archive all files 
zipfileobject = zipfile.ZipFile('E:\Samplefolder\Archive.zip', 'w', zipfile.ZIP_DEFLATED)
dirpath = 'E:\SampleFolder\Archive'

#-Loop thru all files in directory & subdirectories
for root, dirs, files in os.walk(dirpath):

    #-Process aech file
    for file in files:
        
        #-Get archive structure
        sArchivePath = os.path.relpath(os.path.join(root, file),os.path.join(dirpath, '..'))
        print(sArchivePath)
        
        #-Add file to Zip archive
        zipfileobject.write(os.path.join(root, file),sArchivePath)
                            
#-Process completed
zipfileobject.close()
print("All Files in Directory are Zipped")

Mention the full path of the folder to be archived or zipped. Also the name of the archive file to be created.

On these 2 parameters are the input to this above code. This Python code sample is tested in Windows 10 & Python 3.8 (32) version. Hope it works fine for your environment as well.

External Reference: To know more about this zipfile.write function – refer this page.

Os.walk is a unique way to browse throug thru all the files and sub folder in a root directory. It gives the file name, directory name and its root path as well. This has actually reduced lot of coding effort. In many programming languages, this part of looping thru all files in a directory is not a single line code.