2

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?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Evelyn Jeba
  • 4,181
  • 3
  • 12
  • 10
  • I don't believe `zipfile` has that capability. you could theoretically use `zlib` and try to parse the "[central directory](https://en.wikipedia.org/wiki/Zip_(file_format)#Structure)" yourself, but unless these files are prohibitively large and you have a lot of them, I wouldn't go to all that trouble. I'll keep looking for a more reasonable soln. though – Aaron Sep 21 '16 at 13:24
  • 1
    Tried [`ZipFile.infolist`](https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.infolist)? – metatoaster Sep 21 '16 at 13:43
  • @metatoaster a quick test I did indicates that this even spits out files in a predictable order (depth first alphabetical) confirm? deny? thoughts? – Aaron Sep 21 '16 at 13:53
  • What do you mean by without "extracting the zip file"? Those methods provide a list and in order to produce the list the manifest have to be extracted first... – metatoaster Sep 21 '16 at 13:59

2 Answers2

1
import zipfile

with zipfile.ZipFile(zipfilepath, 'r') as myzip:
   print(myzip.printdir())
ivan7707
  • 1,146
  • 1
  • 13
  • 24
1

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.

Evelyn Jeba
  • 4,181
  • 3
  • 12
  • 10