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

Python项目中如何从不同目录导入JSON配置文件?

解决方案

先明确你的项目结构(示例):

your_project/
├── configuration/
│   ├── __init__.py
│   └── defaults/
│       ├── __init__.py
│       ├── config1.json
│       ├── config2.json
│       └── some_module.py
└── another_package/
    ├── __init__.py
    └── your_script.py  # 需要读取JSON的文件

推荐方法:用Python标准库读取包内资源(不依赖工作目录)

Python 3.9+(推荐,用标准库importlib.resources)

直接在another_package/your_script.py里写:

import json
from importlib.resources import files

# 定位到configuration.defaults子包下的JSON文件
json_file = files("configuration.defaults").joinpath("config1.json")
with open(json_file, "r", encoding="utf-8") as f:
    config_data = json.load(f)

# 测试输出
print(config_data)

Python 3.7-3.8(需要安装兼容库)

先执行pip install importlib-resources,然后代码和上面几乎一致:

import json
from importlib_resources import files

json_file = files("configuration.defaults").joinpath("config1.json")
with open(json_file, "r", encoding="utf-8") as f:
    config_data = json.load(f)

兼容旧版本(用pkg_resources,依赖setuptools)

如果你的环境里已经有setuptools(大部分Python环境默认都有),可以这么写:

import json
import pkg_resources

# 读取JSON内容,返回字节串,再转成字典
json_bytes = pkg_resources.resource_string("configuration.defaults", "config1.json")
config_data = json.loads(json_bytes.decode("utf-8"))

print(config_data)

为什么你之前的方法不好用?

  • sys.path.insert:手动插入路径容易因为项目结构调整失效,而且不符合Python包的规范。
  • os.chdir:完全依赖脚本的运行目录,一旦从其他位置启动脚本,路径就会出错,根本不适合包内资源的读取。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 06:40:52