'Not yielding files inside nested folders using python zipfile

(Python 3.8, zipfile module, Windows 10 Anaconda)

I was using the zipfile module of python to create Zip Files of my folders.

My Folder was D:/Personals. An os.listdir of personals yields 2 folders and 171 files. When I checked the zip it contained all the 171 files of the folder and the 2 inner nested folders. But the inner nested folders were empty, though each contained many individual files. Here is my code.

from zipfile import ZipFile 
from os import listdir 

dir_path = 'D:/Personals'
export_path = 'D:/Zipper'

items_list = listdir(dir_path)
zipper = ZipFile(export_path+'/S1.zip','w')

for item in items_list:
    zipper.write(dir_path+'/'+item)

zipper.close()

It has yielded all the files inside the folder but failed to return the files inside the 2 nested folders. Kindly advise what can I do?



Solution 1:[1]

When zipping folders using the ZipFile module, you must use recursion to include the subfolders.

Try this code:

from zipfile import ZipFile 
from os import listdir, path

dir_path = 'D:/Personals'  # root folder to zip
export_path = 'D:/Zipper'  # target folder for zip file

items_list = listdir(dir_path)
zipper = ZipFile(export_path+'/S1.zip','w')

def addzipitems(zipper, folder):  # single folder
    for item in listdir(folder):  # each item (file or folder)
        zipper.write(folder+'/'+item)  # add item to zip (for folder, will add empty)
        if path.isdir(folder +'/'+item):  # if item is subfolder
            addzipitems(zipper, folder +'/'+item)   # process subfolder

addzipitems(zipper, dir_path)  # start at root folder
zipper.close()

You can also use os.walk to get all the files in a directory tree. No recursion needed.

from zipfile import ZipFile 
from os import listdir, path, walk

dir_path = 'D:/Personals'  # root folder to zip
export_path = 'D:/Zipper'  # target folder for zip file

zipper = ZipFile(export_path+'/S1.zip','w')

for path, directories, files in walk(dir_path): # all folders\files in tree
    for f in files:  # files is list
        zipper.write(path+'/'+f)

zipper.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1