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

Python3使用pandas读取指定路径最新CSV报NotADirectoryError如何解决

错误原因

NotADirectoryError触发的核心原因是 os.listdir(path)[-1] 取到的条目不是子目录,而是普通文件,你在后续强行拼接了/作为路径传入os.listdir(),系统识别到目标是文件而非目录,就会抛出该异常。

常见诱因补充
  • os.listdir()返回的是目标路径下所有文件、子目录的名称列表,默认按字符串字典序排序,而非按创建/修改时间排序
  • 手动拼接路径容易出现分隔符错误,且不支持跨平台运行
  • 没有对路径条目类型做校验,直接取最后一项当作目录处理

注意:原代码中默认os.listdir()返回值的最后一项为最新条目是错误逻辑,字符串排序和时间排序完全不同,必须通过修改/创建时间字段做排序才能拿到最新文件

修正后的代码
import pandas as pd
import os

path = '/filepath/'

# 先获取路径下所有子目录,按修改时间倒序排列
dir_list = []
for entry in os.listdir(path):
    full_entry_path = os.path.join(path, entry)
    if os.path.isdir(full_entry_path):
        # 记录(修改时间, 目录完整路径)
        dir_list.append((os.path.getmtime(full_entry_path), full_entry_path))

if not dir_list:
    raise FileNotFoundError(f"路径{path}下无可用子目录")

# 取修改时间最新的子目录
latest_date_dir = sorted(dir_list, reverse=True)[0][1]

# 再获取该子目录下所有CSV文件,按修改时间倒序排列
csv_list = []
for entry in os.listdir(latest_date_dir):
    full_entry_path = os.path.join(latest_date_dir, entry)
    if os.path.isfile(full_entry_path) and entry.lower().endswith('.csv'):
        csv_list.append((os.path.getmtime(full_entry_path), full_entry_path))

if not csv_list:
    raise FileNotFoundError(f"路径{latest_date_dir}下无可用CSV文件")

# 取最新的CSV文件读取
latest_csv_path = sorted(csv_list, reverse=True)[0][1]
csv_to_read = pd.read_csv(latest_csv_path)
display(csv_to_read)
代码说明
  • 用os.path.isdir()校验条目类型,确保只取子目录
  • 用os.path.getmtime()按目录修改时间排序,确保取到的是最新的子目录,而非字典序最后的条目
  • 用os.path.join()拼接路径,自动适配不同系统的路径分隔符
  • 增加空值判断,避免路径下无符合条件的目录/文件时报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:54:03