Python遍历目录读取Excel文件时出现FileNotFoundError的问题求助
解决pd.read_excel()的FileNotFoundError问题
嗨,这个问题我太熟了!你遇到的问题核心在于文件名没有完整路径——os.walk遍历出来的file只是单纯的文件名,而不是文件的实际完整路径。当你直接把file传给pd.read_excel()时,Python会在当前脚本的工作目录下去找这个文件,而不是它实际所在的root目录,自然就找不到啦。
解决方案:拼接完整文件路径
你只需要用os.path.join()把当前遍历的目录路径root和文件名file拼接起来,生成完整的文件路径,再传给pd.read_excel()就可以正常读取了。
修改后的完整代码
import os import pandas as pd # 建议变量名不要用dir,避免和Python内置函数冲突 target_dir = "/home/geta/kelo/eXP/Test/corpus" for root, subdirs, files in os.walk(target_dir): print(root) for file in files: print("-----File in processed :", file) # 拼接文件完整路径 full_file_path = os.path.join(root, file) # 使用完整路径读取Excel文件 sentences = pd.read_excel(full_file_path, sheet_name=0) data_id = sentences.identifiant print("Total phrases: ", len(data_id)) data = sentences.verbatim data_label = sentences.etiquette print("etiquette :", sentences['etiquette'].unique()) classes = sentences['etiquette'].unique() len_classes = len(classes)
额外小提示
- 尽量别用
dir当变量名,它是Python的内置函数(用于查看对象属性),容易引发不必要的混淆。 - 如果目录里有非Excel文件,可以加个过滤判断:
if file.endswith(('.xlsx', '.xls')):,只处理Excel格式的文件,避免无效操作。
内容的提问来源于stack exchange,提问作者kely789456123
相关产品推荐
相关产品推荐

