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

Python中处于lib子目录时如何引用上级主目录的文件路径?

路径引用解决方案

方法1:使用os模块实现(全Python版本兼容)

通过当前脚本文件的固定路径反向推导项目根目录,代码示例如下:

import os
import configparser

# 获取当前py文件的绝对路径
current_script_path = os.path.abspath(__file__)
# 获取当前文件所在的lib目录路径
lib_dir = os.path.dirname(current_script_path)
# 获取上级项目根目录路径
root_dir = os.path.dirname(lib_dir)
# 拼接得到配置文件的完整路径
config_file_path = os.path.join(root_dir, "run.def")

# 读取配置
config = configparser.ConfigParser()
config.read(config_file_path)

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

pathlib是Python3.4后新增的面向对象路径处理模块,写法更直观:

from pathlib import Path
import configparser

# 链式推导得到项目根目录
root_dir = Path(__file__).parent.parent.resolve()
# 拼接配置文件路径
config_file_path = root_dir / "run.def"

# 读取配置
config = configparser.ConfigParser()
config.read(config_file_path)

注意事项

  • 不要直接使用硬编码的相对路径../run.def:该写法仅在工作目录为lib目录时生效,若你在其他目录(如项目根目录)执行脚本,相对路径会基于执行目录计算,导致找不到配置文件
  • 基于__file__变量计算路径的方案最稳妥:__file__保存的是当前py文件的固定绝对路径,不受脚本执行时的工作目录影响,无论在哪个目录启动项目,都能正确定位到配置文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 09:57:04