Computer >> Computer tutorials >  >> Programming >> Python

How to create a zip file using Python?


Use the zipfile module to create a zip archive of a directory. Walk the directory tree using os.walk and add all the files in it recursively.

For example

import os
import zipfile
def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))
zipf = zipfile.ZipFile('Zipped_file.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('./my_folder', zipf)
zipf.close()

The above code will zip the contents of my_folder in a file 'Zipped_file.zip'. and store it in the current directory.