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

遍历子目录读取Zip文件时遇WindowsPath等错误求助

遍历目录读取Zip文件的错误修复方案

错误1:TypeError: 'WindowsPath' object is not iterable

问题根源

  • process_files需要接收可迭代的文件路径集合(如列表、生成器),但你传入了单个WindowsPath对象(p),函数内部for file in files会尝试迭代路径对象,触发类型错误。
  • Path(p.name).glob("*.zip")逻辑错误:p.name仅返回文件/目录的名称,不是完整路径,相当于在当前工作目录下查找,而非目标子目录。

错误2:OSError: [Errno 22] Invalid argument: ''

问题根源

你将单个zip文件路径(字符串)传给了process_files,函数会把字符串当成字符序列迭代,导致ZipFile收到的是单个字符(比如路径的第一个字符\),触发无效参数错误。


正确实现方式

方式1:用Pathlib高效遍历(推荐)

直接通过rglob匹配所有子目录下的zip文件,生成可迭代的路径字符串集合:

from pathlib import Path

target_path = Path("O:/Stack/Over/Flow/")
# 生成所有zip文件的绝对路径字符串迭代器
zip_file_paths = (str(file) for file in target_path.rglob("*.zip"))
# 传入process_files处理
result_df = process_files(zip_file_paths)
print(result_df)

方式2:修复os.walk代码

先收集所有zip文件路径,再传入函数:

import os

dir_path = "O:/Stack/Over/Flow/"
zip_files = []
for root, _, files in os.walk(dir_path):
    for filename in files:
        if filename.endswith(".zip"):
            zip_files.append(os.path.join(root, filename))
# 传入完整的文件路径列表
result_df = process_files(zip_files)
print(result_df)

函数优化建议

原函数的类型提示files: list过于严格,改为支持所有可迭代类型的Iterable[str],适配更广泛的输入:

from typing import Iterable

def process_files(files: Iterable[str]) -> pd.DataFrame:
    # 原函数内部逻辑保持不变
    ...

内容的提问来源于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 13:55:15