How can i list only the folders in zip archive in

2020-08-15 04:09发布

问题:

How can i list only the folders from a zip archive? This will list every folfder and file from the archive:

import zipfile
file = zipfile.ZipFile("samples/sample.zip", "r")
for name in file.namelist():
    print name

Thanks.

回答1:

One way might be to do:

>>> [x for x in file.namelist() if x.endswith('/')]
<<< ['folder/', 'folder2/']


回答2:

I don't think the previous answers are cross-platform compatible since they're assuming the pathsep is / as noted in some of the comments. Also they ignore subdirectories (which may or may not matter to Pythonpadavan ... wasn't totally clear from question). What about:

import os
import zipfile

z = zipfile.Zipfile('some.zip', 'r')
dirs = list(set([os.path.dirname(x) for x in z.namelist()]))

If you really just want top-level directories, then combine this with agroszer's answer for a final step:

topdirs = [os.path.split(x)[0] for x in dirs]

(Of course, the last two steps could be combined :)



回答3:

In python 3, this assumes absolute paths are fed to ZipFile:

from zipfile import ZipFile

zip_f = ZipFile("./Filename.zip")

# All directories:
for f in zip_f.namelist():
    zinfo = zip_f.getinfo(f)
    if(zinfo.is_dir()):
        print(f)

# Only root directories:
root_dirs = []
for f in zip_f.namelist():
    zinfo = zip_f.getinfo(f)
    if zinfo.is_dir():
        # This is will work in any OS because the zip format
        # specifies a forward slash.
        r_dir = f.split('/')
        r_dir = r_dir[0]
        if r_dir not in root_dirs:
            root_dirs.append(r_dir)
for d in root_dirs:
    print(d)


回答4:

more along the lines

set([os.path.split(x)[0] for x in zf.namelist() if '/' in x])

because python's zipfile does not store just the folders