Skip to main content
 首页 » 编程设计

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

2025年05月04日14zdz8207

我有以下 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 中的某种数据结构中。可能吗?

请您参考如下方法:

正如 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”中的文件...