在Python中访问不同文件夹中的类
我想在我的脚本中访问一个配置类。这个配置类在一个文件夹里,那个文件夹在上一级目录的一个单独文件夹中。我的文件夹和文件组织结构如下:
.
├── configs
│ ├── config.json
│ ├── config_manager.py
│ └── __init__.py
└── simulaton_scripts
└── test_script.py
需求:我的程序在 test_script.py
文件中,我想访问在 config_manager.py
文件里的 ConfigurationManager
类。
我尝试在 configs
文件夹里放一个 __init__.py
文件,内容如下:
from . import configs
from .configs import *
最小可重现示例:
import numpy as np
# Config
from configs.config_manager import ConfigurationManager as cfg
上面的代码抛出了一个异常:
发生异常:ModuleNotFoundError (注意:完整的异常追踪信息已显示,但执行在以下位置暂停:) 没有名为 'configs' 的模块 文件 "D:\code\test_script.py",第 9 行,(当前帧) from configs.config_manager import ConfigurationManager as cfg ModuleNotFoundError: 没有名为 'configs' 的模块
1 个回答
0
要使用这个类,你需要确保配置文件的目录在你的Python路径中。你可以通过把包含configs和simulation_scripts的上级目录添加到Python路径来实现这一点。
import sys
import os
# Add the parent directory to the Python path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from configs.config_manager import ConfigurationManager as cfg
我觉得这样做应该能解决你的问题。