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

导入读取CSV的类时触发FileNotFoundError,如何用相对路径解决?

解决Python模块导入后相对路径文件找不到的问题

问题核心:单独运行mod/下的Currency类时,工作目录是mod/,../data/iso-4217.csv的相对路径有效;但从项目根目录运行main.py时,工作目录变成了项目根目录,此时../data会指向根目录的上级目录,自然找不到文件。

要解决这个问题,你需要基于模块文件的实际位置来构建相对路径,而非依赖当前工作目录。下面是两种可行的实现方式:

方式一:使用pathlib(推荐,Python 3.4+)

修改Currency类的get_code方法:

import csv
from pathlib import Path

class Currency:
    def __init__(self, country_name: str):
        self.country = country_name
        self.code = self.get_code()

    def get_code(self) -> str:
        # 获取当前模块文件的路径,往上走一级到项目根目录,再拼接目标文件路径
        data_file_path = Path(__file__).parent.parent / "data" / "iso-4217.csv"
        with open(data_file_path, encoding="utf-8") as file:
            country_list = list(csv.reader(file))
            for row in country_list[1:]:
                if row[0] == self.country:
                    return row[1]
        return ""  # 处理找不到对应国家的边界情况

方式二:使用os.path(兼容旧版Python)

如果项目需要兼容Python 3.4以下版本,可采用os.path实现:

import csv
import os

class Currency:
    def __init__(self, country_name: str):
        self.country = country_name
        self.code = self.get_code()

    def get_code(self) -> str:
        # 获取当前模块所在目录的绝对路径
        current_dir = os.path.dirname(os.path.abspath(__file__))
        # 拼接项目根目录到目标文件的路径
        data_file_path = os.path.join(current_dir, "../data/iso-4217.csv")
        # 标准化路径,自动解析../这类相对符号
        data_file_path = os.path.normpath(data_file_path)
        
        with open(data_file_path, encoding="utf-8") as file:
            country_list = list(csv.reader(file))
            for row in country_list[1:]:
                if row[0] == self.country:
                    return row[1]
        return ""

关键说明

  • __file__:代表当前模块文件的实际路径,无论该模块被哪里导入,这个路径都能准确指向模块本身。
  • 两种方式都摆脱了对运行时工作目录的依赖,确保在单独运行模块或从main.py导入时,都能正确定位到data/下的文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 12:07:16