You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python 3.12 zipfile提取复杂压缩包的嵌套层级内容

提取ZIP文件中的嵌套(第二层)压缩内容

原代码仅能提取ZIP文件的顶层内容,要处理第二层嵌套的ZIP文件,需要遍历提取后的文件,识别并逐个解压其中的ZIP文件。以下是修改后的实现:

import os
import zipfile

sourceZip = "你的源ZIP路径"
extractionPath = "你的提取目标路径"

# 提取顶层所有内容
with zipfile.ZipFile(sourceZip, mode="r") as extraction:
    extraction.extractall(extractionPath)

# 遍历提取目录,处理所有嵌套ZIP文件
for root, dirs, files in os.walk(extractionPath):
    for file in files:
        file_full_path = os.path.join(root, file)
        # 判断当前文件是否为ZIP格式
        if zipfile.is_zipfile(file_full_path):
            try:
                # 创建与ZIP文件同名的子目录,避免文件冲突
                nested_extract_dir = os.path.join(root, os.path.splitext(file)[0])
                os.makedirs(nested_extract_dir, exist_ok=True)
                
                # 解压嵌套ZIP文件到指定子目录
                with zipfile.ZipFile(file_full_path, mode="r") as nested_zip:
                    nested_zip.extractall(nested_extract_dir)
                
                # 可选:解压完成后删除原嵌套ZIP文件
                # os.remove(file_full_path)
            except Exception as e:
                print(f"处理文件 {file_full_path} 时出错: {str(e)}")

代码说明:

  1. 顶层提取:先按原逻辑解压源ZIP的所有顶层内容到目标路径。
  2. 递归遍历:使用os.walk遍历目标路径下的所有文件和子目录。
  3. ZIP识别:通过zipfile.is_zipfile判断文件是否为ZIP格式。
  4. 嵌套解压:对每个识别出的嵌套ZIP,创建同名子目录后解压,避免与其他文件重名冲突;同时添加异常捕获,处理ZIP损坏等意外情况。
  5. 可选清理:如果不需要保留原嵌套ZIP文件,可以取消注释os.remove行。

内容的提问来源于stack exchange,提问作者N Jenkins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 19:47:15