Python 从每个模块访问配置文件

Python access config file from every module

我有以下项目结构:

SmartMirror/
|--config.json
|--main.py
|--widgets/
    |--weather/
        |--__init__.py
        |--weather.py
    |--calendar/
        |--__init__.py
        |--calendar.py

我想从每个小部件 python 文件访问 config.json 文件。

我现在做的是使用以下行

CONFIG_PATH = os.path.join(os.path.dirname(os.path.abspath("config.json")), "config.json")

当我从 SmartMirror 目录 运行 main.py 时有效,但如果我直接 运行 来自不同文件夹的 weather.py 它(可以理解)找不到config.json 文件。

我想知道是否有更好、更安全的方法来从每个小部件或我将来添加的任何其他 python 模块访问配置文件。

现在我发现一种更安全的方法是写 os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), "config.json")

还有一个更好的方法来避免使用所有这些 dirname 可以在 this answer

中找到