【问题标题】:Read xml files directly from a zip file using Python使用 Python 直接从 zip 文件中读取 xml 文件
【发布时间】:2016-02-14 18:48:28
【问题描述】:

我有以下 zip 文件结构:

some_file.zip/folder/folder/files.xml

所以我在 zip 文件的子文件夹中有很多 xml 文件。

到目前为止,我已经设法使用以下代码解压缩 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 中的某种数据结构中。有可能吗?

【问题讨论】:

    标签: python python-2.7 zip zipfile


    【解决方案1】:

    正如 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()) 
    

    正如 OP 在评论中希望的那样,只会处理“folder2”中的文件...

    【讨论】:

    • 所以这将提取所有不是文件夹的文件。但是如何从此处的特定文件夹中提取文件?假设我有 some_file.zip/folder1/files 和 some_file.zip/folder2/files,例如,如何仅从文件夹 2 中提取文件?
    【解决方案2】:

    zf.open() 将返回一个类似对象的文件而不提取它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 2020-12-04
      • 2021-09-20
      • 2015-07-17
      • 2012-09-27
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      相关资源
      最近更新 更多