我有一个 zip 文件,其中包含三个 zip 文件,如下所示:
zipfile.zip\
dirA.zip\
a
dirB.zip\
b
dirC.zip\
c
我想提取具有这些名称(dirA、dirB、dirC)的目录中 zip 文件内的所有内部 zip 文件。
基本上,我想以以下模式结束:
output\
dirA\
a
dirB\
b
dirC\
c
我尝试了以下方法:
import os, re
from zipfile import ZipFile
os.makedirs(directory) # where directory is "\output"
with ZipFile(self.archive_name, "r") as archive:
for id, files in data.items():
if files:
print("Creating", id)
dirpath = os.path.join(directory, id)
os.mkdir(dirpath)
for file in files:
match = pattern.match(filename)
new = match.group(2)
new_filename = os.path.join(dirpath, new)
content = archive.open(file).read()
with open(new_filename, "wb") as outfile:
outfile.write(content)
但它只提取 zip 文件,我最终得到:
output\
dirA\
dirA.zip
dirB\
dirB.zip
dirC\
dirC.zip
包括代码段在内的任何建议 都将不胜感激,因为我尝试了很多不同的东西,但没有成功阅读文档。
原文由 Yannis 发布,翻译遵循 CC BY-SA 4.0 许可协议
解压缩 zip 文件时,您可能希望将内部 zip 文件写入内存而不是将它们写入磁盘。为此,我使用
BytesIO
。看看这段代码:
如果你运行
extract("zipfile.zip")
和zipfile.zip
作为:输出应该是: