Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Thanks.

like image 378
Pythonpadavan Avatar asked Jun 28 '11 17:06

Pythonpadavan


2 Answers

One way might be to do:

>>> [x for x in file.namelist() if x.endswith('/')]
<<< ['folder/', 'folder2/']
like image 193
zeekay Avatar answered Sep 30 '22 14:09

zeekay


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

like image 31
Dave B. Avatar answered Sep 30 '22 12:09

Dave B.