Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

zip

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

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

I am using the zipfile library. 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'):
                return zip_file.open(filename)

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

like image 993
Alexander Zhukov Avatar asked Aug 02 '13 11:08

Alexander Zhukov


People also ask

How do I extract a single file from a ZIP file?

Do one of the following: To unzip a single file or folder, open the zipped folder, then drag the file or folder from the zipped folder to a new location. To unzip all the contents of the zipped folder, press and hold (or right-click) the folder, select Extract All, and then follow the instructions.

How do you extract parts of a ZIP file?

To unzip filesOpen File Explorer and find the zipped folder. To unzip the entire folder, right-click to select Extract All, and then follow the instructions. To unzip a single file or folder, double-click the zipped folder to open it. Then, drag or copy the item from the zipped folder to a new location.


2 Answers

This prints the 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 item: directories[0].

like image 135
alecxe Avatar answered Nov 10 '22 11:11

alecxe


Do you want to get directory that 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)
like image 25
falsetru Avatar answered Nov 10 '22 10:11

falsetru