Alexander Zhukov Alexander Zhukov - 4 years ago 178
Python Question

Extracting a single file from a zip archive without iterating over the entire name list in Python

I have a zip file with a folder in it, like this:

I am using the
What I want is to open only some.xml file, but I don't now the some_folder name.
My solution looks like this:

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

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

Answer Source

This prints the list of directories inside the file:

from zipfile import ZipFile

with ZipFile('', '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 item: directories[0].

Hope that helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download