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

Python遍历主压缩包内子压缩目录中文件的实现方法

遍历嵌套压缩文件夹中文本文件的简便方法

可以用Python结合zipfile模块实现,不需要额外安装第三方库,核心逻辑是递归遍历所有层级的文件夹和压缩包,筛选出.txt文件:

实现代码

import os
import zipfile
from io import BytesIO

def find_txt_files(path):
    # 处理压缩文件
    if path.endswith('.zip'):
        with zipfile.ZipFile(path, 'r') as zf:
            for file_info in zf.infolist():
                # 跳过目录项
                if file_info.is_dir():
                    continue
                # 匹配文本文件
                if file_info.filename.endswith('.txt'):
                    print(f"找到文本文件:{file_info.filename}(来源:{path})")
                # 递归处理嵌套的压缩包
                elif file_info.filename.endswith('.zip'):
                    nested_zip_data = zf.read(file_info.filename)
                    with zipfile.ZipFile(BytesIO(nested_zip_data), 'r') as nested_zf:
                        for nested_file in nested_zf.infolist():
                            if not nested_file.is_dir() and nested_file.filename.endswith('.txt'):
                                print(f"找到文本文件:{nested_file.filename}(来源:{path} -> {file_info.filename})")
    # 处理普通文件夹
    elif os.path.isdir(path):
        for item in os.listdir(path):
            item_path = os.path.join(path, item)
            find_txt_files(item_path)
    # 处理单个文本文件
    elif path.endswith('.txt'):
        print(f"找到文本文件:{path}")

# 传入目标压缩包/文件夹路径
find_txt_files('mainfolder.zip')

关键特性

  • 全层级覆盖:不管是普通文件夹里的压缩包,还是压缩包内的嵌套压缩包,都能遍历到
  • 轻量化处理:嵌套压缩包直接读取内存数据,无需额外解压到磁盘
  • 可扩展性强:把print语句替换成文件读取、复制等操作即可适配实际需求

命令行替代方案(Linux/macOS)

如果习惯用命令行,可通过工具组合实现基础遍历:

# 查看主压缩包内的txt文件
unzip -l mainfolder.zip | grep "\.txt$"

# 遍历当前目录下所有zip包内的txt文件
find . -name "*.zip" -exec unzip -l {} \; | grep "\.txt$"

注:命令行方式处理多层嵌套压缩包逻辑较复杂,适合简单场景使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 19:55:18