开发者

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

How can i list only the folders from a zip archive? This will list every folfder and file from the arc开发者_运维百科hive:

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

Thanks.


One way might be to do:

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


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 :)


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜