我的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.py
的Common
包下导入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 可以不需要。