如何在Python中递归提取zip文件

时间:2016-03-29 13:18:54

标签: python python-3.x zip unzip zipfile

我有一个zip文件,其中包含三个zip文件:

SelectedEmployee

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

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

我尝试了以下内容:

output\  
    dirA\
         a  
    dirB\
         b  
    dirC\
         c

但它只提取zip文件,我最终得到:

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)

任何建议,包括代码段都会受到高度赞赏,因为我尝试了很多不同的东西,并且没有成功阅读文档。

4 个答案:

答案 0 :(得分:8)

解压缩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)

如果您将extract("zipfile.zip")zipfile.zip一起投放为:

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

输出应为:

dirA/
  a
dirB/
  b
dirC/
  c

答案 1 :(得分:2)

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

using (var stream = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read))
{
}

答案 2 :(得分:2)

我尝试了其他一些解决方案,但无法使其“就地”工作。我将发布解决方案以处理“就地”版本。注意:它会删除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)使所有这些工作。

答案 3 :(得分:1)

这对我有用。只需将此脚本和嵌套的zip放在同一目录下即可。它将zip提取到与原始zip具有相同名称的目录中,并清理原始zip。它还将计算嵌套zip中的文件总数

import os

from zipfile import ZipFile


def unzip (path, total_count):
    for root, dirs, files in os.walk(path):
        for file in files:
            file_name = os.path.join(root, file)
            if (not file_name.endswith('.zip')):
                total_count += 1
            else:
                currentdir = file_name[:-4]
                if not os.path.exists(currentdir):
                    os.makedirs(currentdir)
                with ZipFile(file_name) as zipObj:
                    zipObj.extractall(currentdir)
                os.remove(file_name)
                total_count = unzip(currentdir, total_count)
    return total_count

total_count = unzip ('.', 0)
print(total_count)