如何递归提取zip文件?

2024-05-14 09:55:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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

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


Tags: 文件idnewoutputosmatchfileszip
3条回答

我尝试了其他一些解决方案,但无法让它们“到位”。我将发布我的解决方案来处理“就地”版本。注意:它删除zip文件,并用同名目录“替换”它们,,因此如果要保留,请备份zip文件

策略很简单。解压目录(和子目录)中的所有zip文件,冲洗并重复,直到没有zip文件保留。如果zip文件包含zip文件,则需要进行冲洗和重复

import os
import io
import zipfile
import re

def unzip_directory(directory):
    """" This function unzips (and then deletes) all zip files in a directory """
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if re.search(r'\.zip$', filename):
                to_path = os.path.join(root, filename.split('.zip')[0])
                zipped_file = os.path.join(root, filename)
                if not os.path.exists(to_path):
                    os.makedirs(to_path)
                    with zipfile.ZipFile(zipped_file, 'r') as zfile:
                        zfile.extractall(path=to_path)
                    # deletes zip file
                    os.remove(zipped_file)

def exists_zip(directory):
    """ This function returns T/F whether any .zip file exists within the directory, recursively """
    is_zip = False
    for root, dirs, files in os.walk(directory):
        for filename in files:
            if re.search(r'\.zip$', filename):
                is_zip = True
    return is_zip

def unzip_directory_recursively(directory, max_iter=1000):
    print("Does the directory path exist? ", os.path.exists(directory))
    """ Calls unzip_directory until all contained zip files (and new ones from previous calls)
    are unzipped
    """
    iterate = 0
    while exists_zip(directory) and iterate < max_iter:
        unzip_directory(directory)
        iterate += 1
    pre = "Did not " if iterate < max_iter else "Did"
    print(pre, "time out based on max_iter limit of", max_iter, ". Took iterations:", iterate)

假设您的zip文件已备份,则可以通过调用unzip_directory_recursively(your_directory)来实现这一切

对于提取嵌套zip文件(任何级别的嵌套)并清理原始zip文件的函数:

import zipfile, re, os

def extract_nested_zip(zippedFile, toFolder):
    """ Extract a zip file including any nested zip files
        Delete the zip file(s) after extraction
    """
    with zipfile.ZipFile(zippedFile, 'r') as zfile:
        zfile.extractall(path=toFolder)
    os.remove(zippedFile)
    for root, dirs, files in os.walk(toFolder):
        for filename in files:
            if re.search(r'\.zip$', filename):
                fileSpec = os.path.join(root, filename)
                extract_nested_zip(fileSpec, root)

提取zip文件时,您可能希望将内部zip文件写入内存,而不是写入磁盘。为此,我使用了^{}

查看此代码:

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

相关问题 更多 >

    热门问题