Search code examples
pythondirectoryzippython-zipfile

How to list a folder's files using the zipfile module in Python


I'm having a .zip file which contains lots of files and directories in it. Its structure resembles the following sketch.

/
contents/
  --file1.txt
  --file2.txt
lists/
  --file3.txt
  --file4.txt
file5.txt
file6.txt

I am currently interested on listing (and reading) the files residing on the particular subfolder called contents.

However I can't seem to find a useful function to do that since the zipfile module's namelist function will just list every signle file. The only other way I can think of is to extract everything on a temp folder read what I need to and then delete it. But I consider it a dumb approach.

Any other ideas?


Solution

  • Filter it.

    dirfiles = [f for f in z.namelist() if f.startswith(pathprefix)]