我有这样的目录结构
dir1/subdir1/module1.py
dir1/subdir2/subdir22/module2.py
假设我将 __init__.py 添加到每个目录和子目录中。我想从模块2导入模块1,在引用相关问题并尝试不同的方法后,我找不到解决方案。例如
在模块2中我尝试导入模块1,例如
from .... import subdir1.module1
from ....subdir1 import module1
上述两个导入都会引发语法错误。
最佳答案
这对我有用,
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.dirname(path.dirname(path.abspath(__file__))) ) ) )
from dir1.subdir1 import module1
关于python - 从父目录的子目录导入 python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30202267/