如何在两个子目录中导入 python 个文件

How to import python files within two subdirectories

我的目录结构如下

 - src\module1\ __init__.py 
 - src\module1\foo1.py 
 - src\module2\ __init__.py
 - src\module2\foo2.py

我想在 foo2.py 中导入 foo1.py 的函数。我尝试使用

导入
from module1.foo1 import *

但这是抛出回溯错误。 请建议如何在 foo2.py

中导入 foo1.py

提前致谢 手册

试试这个

from module1.foo1 import ClassName

来自https://docs.python.org/2/tutorial/modules.html

6.1.2. The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

the directory containing the input script (or the current directory).

PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

the installation-dependent default.

After initialization, Python programs can modify sys.path.

所以让我们修改sys.path

import sys
sys.path.append('src\module1\')
import foo1

它值得打印 sys.path 这样您就可以了解为什么还没有找到它。