Vasily Vasily - 1 year ago 56
Python Question

os.listdir analog for a zipped directory

My goal is to list all files contained in the certain sub-directory inside a zip-archive.

raises a
, and
just lists all the files in all directories.

Any ideas?


Try the following:

files = list(filter(lambda f: f.startswith("subdir"), zfile.namelist()))


Explanation: filter filters the list supplied by zfile.namelist() on a lambda that is checking whether the filename starts with "subdir".

The filter function does not return a list but rather a filter object (generator) and thus we need to convert it to a list.

You could also use the following line which does the same but uses list comprehension:

files = [f for f in zfile.namelist() if f.startswith("subdir")]

Edit: As pointed out by advance512: "The problem with this solution is that it will also return files in subdirectories inside the subdirectory you're checking.":

files = [f for f in zfile.namelist() if f.startswith("subdir") and f.count("/") == 1]

This will not return any files in sub-sub directories.