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

Python跨目录调用模块时配置文件路径适配的优雅解决方案

解决Python模块跨场景调用的配置文件路径问题

问题场景

文件夹结构:

root
|-config
  |-config.ini
|-src
  |-A
    |-file1.py
  |-file2.py

file2.py原本通过相对路径../config/config.ini读取配置,直接运行file2时正常,但当file1通过from src.file2 import MyModule导入并初始化MyModule时,会出现配置文件找不到的问题;修改路径为../../config/config.ini又无法适配直接运行file2的场景。

简洁解决方案:基于模块自身路径推导绝对路径

核心思路是通过模块文件的绝对路径,动态计算配置文件的位置,不受运行时工作目录的影响,完美适配两种调用场景。

方法1:使用os模块(兼容Python2/3)

修改file2.py的配置读取逻辑:

# file2.py
import os
import configparser

class MyModule:
    def __init__(self, ...):
        # 获取当前模块文件的绝对目录(src目录)
        current_module_dir = os.path.dirname(os.path.abspath(__file__))
        # 拼接并标准化配置文件路径
        config_path = os.path.normpath(os.path.join(current_module_dir, "../config/config.ini"))
        
        config = configparser.ConfigParser()
        config.read_file(open(config_path))
        # 后续业务逻辑...

方法2:使用pathlib(Python3.4+推荐,更简洁)

利用pathlib的面向对象路径操作:

# file2.py
from pathlib import Path
import configparser

class MyModule:
    def __init__(self, ...):
        # 当前模块文件的父目录即src目录
        src_dir = Path(__file__).parent
        # 从src目录向上到root,再进入config目录获取配置文件
        config_path = src_dir.parent / "config" / "config.ini"
        
        config = configparser.ConfigParser()
        config.read_file(open(config_path))
        # 后续业务逻辑...

进阶:可配置路径参数(更灵活)

如果需要支持手动指定配置路径,可给MyModule增加可选参数:

# file2.py
from pathlib import Path
import configparser

class MyModule:
    def __init__(self, config_path=None, ...):
        if config_path is None:
            src_dir = Path(__file__).parent
            config_path = src_dir.parent / "config" / "config.ini"
        
        config = configparser.ConfigParser()
        config.read_file(open(config_path))
        # 后续业务逻辑...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 21:45:36