How can I list only folders in a zip archive in Python?

How can I list only folders from a zip archive? This list will list all files and files from the archive:

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

Thanks.

+6
source share
4 answers

One way can be done:

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

I don't think the previous answers are cross-platform compatible, as they assume that pathsep / , as noted in some comments. They also ignore subdirectories (which may or may not matter to Pythonpadavan ... were not completely clear from the 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 need top-level directories, combine this with agroszer for the last step:

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

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

+1
source

longer along the lines

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

because the python zip file does not only store folders

0
source

In python 3:

 from zipfile import ZipFile # All directories: for f in zip_ref.namelist(): zinfo = zip_ref.getinfo(f) if(zinfo.is_dir()): print(f) # Only root directories: root_dirs = [] zip_ref = ZipFile("ZipFile.zip") for f in zip_ref.namelist(): zinfo = zip_ref.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) 
0
source

Source: https://habr.com/ru/post/891573/


All Articles