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

遍历子目录查找sample4.csv触发FileNotFoundError,求Python解决方法

解决访问子目录CSV文件触发的FileNotFoundError

问题场景

父文件夹中存在MyFile.py文件,需访问data/AWSyearly/2021子目录下的sample4.csv文件,使用os.path编写代码后运行触发FileNotFoundError。

文件夹结构

C:.
├───1. Parent Folder : 
│       'Myfile.py'

   ├───2. 'data'  (subfolder1)

       ├───3. 'AWSyearly'                      (subfolder2)
           ├───3.1. '2020'                     (folder within 'yearlydata_subfolder2')
               sample1.csv                     (file in folder '2020')
               ├───3.1.1 monthlydata_2020      (subfolder within 2020)
                   sample2_2020_Jan.csv
                   sample3_2020_Feb.csv

           ├───3.2 '2021'                      (folder within 'yearlydata_subfolder2')
               sample4.csv                     (file in folder '2021') 
               ├───3.2.1 monthlydata_2021      (subfolder within 2021)
                   sample5_2021_Jan.csv
                   sample6_2021_Feb.csv

用户原代码

def access_csv():
    path = os.path.realpath(os.path.join(os.getcwd(),os.path.dirname(__file__)))
    print("Path of csv is:", path)
    for root, dirs, files in os.walk(path):
        for file in files:
            if file.startswith('sample4') and file.endswith(".csv"):
                df = pd.read_csv(file, decimal=",", delimiter=";", index_col=0)
    return df

问题原因

  1. 文件路径不完整:os.walk返回的file仅为文件名,不是完整路径,pd.read_csv(file)会在当前工作目录下查找文件,自然找不到目标文件。
  2. 路径构造冗余:os.path.dirname(__file__)已经是脚本所在的父文件夹路径,无需再与os.getcwd()拼接。

解决方案

方案1:修正os.walk的路径拼接

保留遍历逻辑,通过root和file拼接完整文件路径:

import os
import pandas as pd

def access_csv():
    # 获取当前脚本所在的父文件夹路径
    script_dir = os.path.dirname(os.path.realpath(__file__))
    print("脚本所在路径:", script_dir)
    for root, dirs, files in os.walk(script_dir):
        for file in files:
            if file == 'sample4.csv':  # 直接匹配文件名更准确
                # 拼接完整文件路径
                full_file_path = os.path.join(root, file)
                df = pd.read_csv(full_file_path, decimal=",", delimiter=";", index_col=0)
                return df  # 找到文件后直接返回,终止遍历
    # 未找到文件时抛出异常
    raise FileNotFoundError("未找到sample4.csv文件")

方案2:直接构造目标路径(推荐)

已知文件具体位置,无需遍历所有文件,直接拼接路径更高效:

import os
import pandas as pd

def access_csv():
    script_dir = os.path.dirname(os.path.realpath(__file__))
    # 构造目标文件的完整路径
    target_path = os.path.join(script_dir, "data", "AWSyearly", "2021", "sample4.csv")
    print("目标文件路径:", target_path)
    # 先检查文件是否存在
    if not os.path.exists(target_path):
        raise FileNotFoundError(f"文件不存在: {target_path}")
    df = pd.read_csv(target_path, decimal=",", delimiter=";", index_col=0)
    return df

方案2优势:代码简洁,避免不必要的目录遍历,执行效率更高,适合已知文件具体位置的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 13:15:24