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

为何pd.ExcelFile报文件找不到错误而pd.read_excel可正常运行?

pd.ExcelFile报错但pd.read_excel正常的原因分析

核心原因是你调用pd.ExcelFile时传入的文件路径不完整或错误,而调用pd.read_excel时用了正确的完整路径。

具体场景拆解

当用os.walk遍历主文件夹时,返回的files列表里只有纯文件名,不包含所在子文件夹的路径。如果直接把这个纯文件名传给pd.ExcelFile,程序会在当前工作目录(不是文件实际所在的子文件夹)中查找,自然找不到目标文件,抛出FileNotFoundError。

而你使用pd.read_excel时,应该是正确通过os.path.join(root, filename)拼接了文件的完整绝对路径,所以能正常定位并读取文件。

错误与正确代码示例

错误的pd.ExcelFile用法(导致报错)

import os
import pandas as pd

main_path = "/你的主文件夹绝对路径"
for root, dirs, files in os.walk(main_path):
    for file in files:
        if file.endswith(".xlsx"):
            # 仅传入文件名,未拼接子文件夹路径
            excel_obj = pd.ExcelFile(file)
            df = excel_obj.parse("test")

正确的pd.ExcelFile用法(与pd.read_excel逻辑一致)

import os
import pandas as pd

main_path = "/你的主文件夹绝对路径"
for root, dirs, files in os.walk(main_path):
    for file in files:
        if file.endswith(".xlsx"):
            # 拼接完整文件路径
            full_file_path = os.path.join(root, file)
            excel_obj = pd.ExcelFile(full_file_path)
            df = excel_obj.parse("test")

补充说明

pd.read_excel本质上内部会先创建ExcelFile对象再解析工作表,两者对文件路径的要求完全一致,不存在某一方能自动补全路径的特性。出现差异的唯一原因就是调用两者时传入的路径参数不同。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 22:24:59