在zip文件中打开嵌套文件夹的问题-python 3.6

问题描述

我需要分析大量zip档案,这些档案也嵌套在zip文件中。文件结构很奇怪,我找不到将文件一一解压到相应文件夹的正确方法

我可以打开最外面的拉链,即:xxx-xxxxxx-x-xx-xx_20200913_003310_coll_diag.zip

xxx-xxxxxx-x-xx-xx这部分是收集文件的节点主机名。

父zip文件包含一个名为diagnostic_information文件夹。 我使用以下代码diagnostic_information文件提取xxx-xxxxxx-x-xx-xx_20200913_003310_coll_diag中,因此此时的路径结构如下:

xxx-xxxxxx-x-xx-xx_20200913_003310_coll_diag\diagnostic_information

def def_extract_files_from_zip_msml(parent_zip_name: str,files_to_unzip: list):
    import zipfile
    import os
    import re

    # extracts the main zipfile into the 'parent_folder_name/diagnostic_information/' #
    parent_folder_name = re.search(r'(^ipi-.*)\.zip',parent_zip_name).group(1)
    path_to_diag_folder = f'{os.path.expanduser("~")}\\Documents\PycharmProjects\\' \
                          f'{parent_folder_name}\\diagnostic_information\\'
    with zipfile.ZipFile(parent_zip_name,'r') as zipObj:
        zipObj.extractall(path=parent_folder_name)
    os.chdir(path_to_diag_folder)
    #print(os.getcwd())

diagnostic_information文件夹中,有几个具有不同名称的zip文件,但是,在每个这些zip文件中,都有一个名为tempdir文件夹,其中包含.log文件。这些.log文件存在于所有较高级别的文件夹中,因为该设备具有多个插槽,并且日志文件名相同。 如果要执行zipxx.extractall(),我将覆盖大多数文件,并且我将不知道日志文件属于哪个插槽。 我尝试指定首先将哪个zip文件提取到名为该文件的目录中,但是代码返回错误

KeyError:“存档中没有名为'slot_12.zip'的项目”

下面的代码是第一个代码的一部分:

for file in files_to_unzip:
    filename = re.search(r"[^_](slot_\d+\.zip$)",file).group(1)
    dest_folder = re.search(r"[^_](slot_\d+)\.zip$",file).group(1)
    full_path_to_file = f'{os.path.expanduser("~")}\\Documents\PycharmProjects\\' \
                        f'{parent_folder_name}\\diagnostic_information\\{filename}'
    with zipfile.ZipFile(full_path_to_file,'r') as zipObj2:
        zipObj2.extract(member=filename,path=dest_folder)

最佳的解决方案是将主归档文件加载到内存中,仅将指定的内部归档文件提取到以下路径:/xxxxxx-x-xx-xx_20200913_003310_coll_diag/slot_2/

提取的示例文件

xxxxxx-x-xx-xx_20200913_003310_coll_diag/diagnostic_information/slot_2.zip/tempdir/*.log

收件人:

xxxxxx-x-xx-xx_20200913_003310_coll_diag/slot_2/

我正在使用Windows,但是如果代码仅在Linux上可以运行,则可以。

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)