5

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.

4

2 回答 2

10

这将打印文件内的目录列表test.zip

from zipfile import ZipFile


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

如果你知道里面只有一个目录,就取第一项:directories[0].

希望有帮助。

于 2013-08-02T11:43:32.403 回答
2

你想得到包含的目录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)
于 2013-08-02T11:43:35.470 回答