How to zip a folder recursively using Python?

PythonServer Side ProgrammingProgramming

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. 

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.

raja
Published on 27-Dec-2017 10:44:06
Advertisements