使用Python直接从zip文件中读取xml文件

4

我有以下的zip文件结构:

some_file.zip/folder/folder/files.xml

因此,我有很多xml文件在zip文件的子文件夹中。

到目前为止,我已经使用以下代码成功解压了zip文件:

import os.path
import zipfile

with zipfile.ZipFile('some_file.zip') as zf:
    for member in zf.infolist():
        # Path traversal defense copied from
        # http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
        words = member.filename.split('/')
        path = "output"
        for word in words[:-1]:
            drive, word = os.path.splitdrive(word)
            head, word = os.path.split(word)
            if word in (os.curdir, os.pardir, ''): continue
            path = os.path.join(path, word)

        zf.extract(member, path)

但我不需要从压缩文件中提取文件,而是直接从zip文件中读取它们。因此,要么在for循环中读取每个文件并处理它,要么将每个文件保存在Python中某种数据结构中。这是否可能?

2个回答

8

如Robin Davis所写,zf.open()可以实现此功能。以下是一个小例子:

import zipfile

zf = zipfile.ZipFile('some_file.zip', 'r')

for name in zf.namelist():
    if name.endswith('/'): continue

    if 'folder2/' in name:
        f = zf.open(name)
        # here you do your magic with [f] : parsing, etc.
        # this will print out file contents
        print(f.read()) 

如评论中所希望的,只有来自“folder2”文件夹的文件将被处理...


这将提取所有不是文件夹的文件。但是我如何从特定文件夹中提取文件呢?比如说,我有some_file.zip/folder1/files和some_file.zip/folder2/files,我该如何仅从folder2中提取文件呢? - Ivan Bilan

5

zf.open()会返回一个类似于文件对象的内容,但并不会将其解压。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接