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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With