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

Python提取Zip内Excel行数遇KeyError及子目录适配问题求助

问题排查与解决方案

一、KeyError: "There is no item named 'Test1' in the archive" 问题排查

这个错误的核心是代码中指定的文件名/路径在压缩包内不存在,按以下步骤快速定位:

  1. 先确认压缩包内的实际文件结构:
    临时在代码中添加一行,打印压缩包内所有文件的完整路径(包括子目录):
    import zipfile
    with zipfile.ZipFile("你的压缩包路径.zip", 'r') as zf:
        print(zf.namelist())  # 输出所有文件的完整路径
    
    对比输出结果和你代码里写的Test1,大概率是这几种情况:
    • 文件名漏加后缀:比如实际是Test1.xlsx,你写了Test1
    • 文件在子目录中:比如实际路径是data/Test1.xlsx,你直接写了Test1
    • 大小写不匹配:比如实际是test1.xlsx,你写了Test1(Linux/macOS下大小写敏感)
    • 代码硬编码了错误文件名,压缩包里根本没有这个文件
  2. 批量处理场景排查:如果代码是遍历多个压缩包,可能部分包里没有Test1文件,需添加存在性判断后再读取。

二、适配含子目录(如2022-05、2022-06)的场景

分两种子目录场景适配,以下是完整可运行的代码示例:

完整适配代码

import os
import zipfile
import pandas as pd

def count_excel_rows_in_zip(zip_path):
    total_rows = 0
    with zipfile.ZipFile(zip_path, 'r') as zf:
        # 遍历压缩包内所有文件,包括子目录中的文件
        for file_name in zf.namelist():
            # 过滤Excel格式文件(支持.xlsx/.xls/.xlsm)
            if file_name.endswith(('.xlsx', '.xls', '.xlsm')):
                with zf.open(file_name) as f:
                    # 读取Excel并统计行数(如需包含表头,去掉header=None)
                    try:
                        df = pd.read_excel(f, engine='openpyxl')  # .xlsx用openpyxl,.xls需安装xlrd
                        total_rows += len(df)
                    except Exception as e:
                        print(f"读取文件 {file_name} 失败:{str(e)}")
                        continue
    return total_rows

def scan_all_zips_in_dir(root_dir):
    total_all = 0
    # 递归遍历本地所有子目录,包括2022-05、2022-06这类子目录
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.zip'):
                zip_full_path = os.path.join(root, file)
                zip_rows = count_excel_rows_in_zip(zip_full_path)
                print(f"压缩包 {zip_full_path} 内Excel总行数:{zip_rows}")
                total_all += zip_rows
    print(f"所有压缩包内Excel总行数:{total_all}")

# 调用示例:替换为你的根目录路径
scan_all_zips_in_dir("./your_root_directory")

关键适配点

  1. 本地子目录遍历:用os.walk()递归扫描所有层级的子目录,自动识别2022-05、2022-06这类目录下的压缩包。
  2. 压缩包内子目录处理:用zf.namelist()获取压缩包内所有文件的完整路径,直接通过后缀过滤Excel文件,无需关心文件在哪个子目录。
  3. 容错增强:添加try-except捕获单个Excel文件的读取错误(如损坏文件),避免程序因单个文件问题崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 12:10:21