python - 如何递归提取zip文件?

标签 python python-3.x unzip zip

我有一个 zip 文件,其中包含三个 zip 文件,如下所示:

zipfile.zip\  
    dirA.zip\
         a  
    dirB.zip\
         b  
    dirC.zip\
         c

我想将 zip 文件中的所有内部 zip 文件提取到具有这些名称(dirA、dirB、dirC)的目录中。
基本上,我想以以下架构结束:

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

任何包括代码段在内的建议将不胜感激,因为我已经尝试了很多不同的东西并且阅读文档都没有成功。

最佳答案

解压缩 zip 文件时,您可能希望将内部 zip 文件写入内存而不是将它们写入磁盘。为此,我使用了 BytesIO .

检查这段代码:

import os
import io
import zipfile

def extract(filename):
    z = zipfile.ZipFile(filename)
    for f in z.namelist():
        # get directory name from file
        dirname = os.path.splitext(f)[0]  
        # create new directory
        os.mkdir(dirname)  
        # read inner zip file into bytes buffer 
        content = io.BytesIO(z.read(f))
        zip_file = zipfile.ZipFile(content)
        for i in zip_file.namelist():
            zip_file.extract(i, dirname)

如果您使用 zipfile.zip 运行 extract("zipfile.zip") 作为:

zipfile.zip/
    dirA.zip/
        a
    dirB.zip/
        b
    dirC.zip/
        c

输出应该是:

dirA/
  a
dirB/
  b
dirC/
  c

关于python - 如何递归提取zip文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36285502/

相关文章:

python - Matplotlib 辅助/双轴 - 用圆圈和箭头标记 - 用于黑白 (bw) 发布

python - 尝试除了递归或 while 循环?

python - 在 tkinter 中呈现菜单

python - Pandas : Compare the columns of a data frame and add a new column & value based on a condition

azure - 如何作为 Azure 数据工厂的一部分解压缩并执行批处理服务作业

python - 为什么Python的类对象的deepcopy()共享类变量?

python - 在 Python 中使用 credstash

python-3.x - 如何在列表或字典中存储来自 Gtk.Calendar.get_date() 的日期和来自 Gtk.TextBuffer 的 python 中该日期的文本

encoding - 压缩或解压缩具有不同文件名编码的文件?

Java ZipFileSystem 在遍历时不保留物理顺序