How can i list only the folders in zip archive in Python?

故事扮演 提交于 2019-12-23 08:34:51

问题


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



来源:https://stackoverflow.com/questions/6510477/how-can-i-list-only-the-folders-in-zip-archive-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!