'Listing all directories recursively within the zipfile without extracting in python

In Python we can get the list of all files within a zipfile without extracting the zip file using the below code.

import zipfile
zip_ref = zipfile.ZipFile(zipfilepath, 'r')
    for file in zip_ref.namelist():
        print file

Similarly is there a way to fetch the list of all directories and sub directories within the zipfile without extracting the zipfile?



Solution 1:[1]

import zipfile

with zipfile.ZipFile(zipfilepath, 'r') as myzip:
   print(myzip.printdir())

Solution 2:[2]

Thanks everyone for your help.

import zipfile

subdirs_list = []
zip_ref = zipfile.ZipFile('C:/Download/sample.zip', 'r')
for dir in zip_ref.namelist():
    if dir.endswith('/'):
        subdirs_list.append(os.path.basename(os.path.normpath(dir)))

print subdirs_list

With the above code, I would be able to get a list of all directories and subdirectoies within my zipfile without extracting the sample.zip.

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 ivan7707
Solution 2 Evelyn Jeba