Friday, January 1, 2021

Creating Zip file for items within multiple folders

 The script below will access all children folders within a parent directory then zip the contents and return back to the parent directory before moving to the next child folder.

The process continue until all children folders are processed.

# list of folders to zip their contents...
folders = glob.glob('*')

# Change dir to the first folder, zip its contents and return back to parent dir...
for folder in folders:
    # Change directory to folder in list of folders...
    os.chdir(folder)
    
    list_files = glob.glob('*')
    with zipfile.ZipFile(folder+'.zip', 'w') as zipF:
        for file in list_files:
            zipF.write(file, compress_type=zipfile.ZIP_DEFLATED)
    
    # Change directory back to main folder...
    os.chdir(r"C:\Users\Yusuf_08039508010\Documents\DandR")

print('Done...')


Note that the script uses the folder's name to name the resulting zip file as seen below.




That is it!

No comments:

Post a Comment