Extract a single file from a zip archive without iterating over an entire list of names in Python

I have a zip file with a folder in it, for example:

some.zip/ some_folder/ some.xml ... 

I am using the zipfile library. I want to open only some.xml file, but now I am not some_folder name. My solution looks like this:

  def get_xml(zip_file): for filename in zip_file.namelist(): if filename.endswith('some.xml'): return zip_file.open(filename) 

I would like to know if there is a better solution besides scanning the entire list.

+4
source share
2 answers

This prints a list of directories inside the test.zip file:

 from zipfile import ZipFile with ZipFile('test.zip', 'r') as f: directories = [item for item in f.namelist() if item.endswith('/')] print directories 

If you know that there is only one directory inside, just take the first element: directories[0] .

Hope this helps.

+9
source

Do you want to get a directory containing some.xml ?

 import os import zipfile with zipfile.ZipFile('a.zip', 'r') as zf: for name in zf.namelist(): if os.path.basename(name) == 'some.xml': print os.path.dirname(name) 
+2
source

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


All Articles