Skip to main content
 首页 » 编程设计

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

2025年02月15日8zhujiabin

我的 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的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 可以没有。