我想在 python 中拥有以下项目目录结构:
project\
generic.py
subdir1\
file1.py
subdir2\
file2.py
subdir3\
file3.py
在 file1.py 中,我想从项目的根目录导入 generic.py。
import generic
不幸的是,当我尝试执行“file1.py”时出现错误
root:~/project/sidir1# python file1.py
Traceback (most recent call last):
File "file1.py", line 7, in <module>
import generic
ImportError: No module named generic
我想执行单个file*.py并包含generic.py。
如何正确地将其包含在这样的目录结构下?
最佳答案
您可以通过在根目录中创建__init__.py
来将您的Python项目打包。
然后您可以使用相对导入,例如:from .. import generic
关于python - python项目中的文件导入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53303202/