Python:如何从兄弟文件夹添加模块



我的Python项目有以下文件夹结构:

pythonApp             --> Folder
|--ABC                --> Package
   |--__init__.py     --> Empty File
   |--abctest.py      --> Module
|--DEF                --> Package
   |--__init__.py     --> Empty File
   |--deftest.py      --> Module
|--Common             --> Package
   |--__init__.py     --> Empty File
   |--constants.py    --> Module

我想在abctest.pyCommon包下导入constants.py。使用 from Common import constants 会引发错误Module not found。有没有解决方案。

abctest.py 中,使用 __file__ 作为当前模块名称将父目录添加到 python 路径,然后取 dirname 的目录来计算它:

import os,sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from Common import constants

注意:Python 2 似乎需要目录中Common一个__init__.py文件(甚至是空的(才能将Common识别为模块,而 Python 3 可以不需要。

最新更新