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

2024-04-27 00:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个目录结构如下

 - 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

提前谢谢 马努


Tags: 函数frompyimportsrc目录init错误
2条回答

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.

所以让我们修改一下系统路径你知道吗

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

值得印刷系统路径所以你可以明白为什么还没有找到。你知道吗

试试这个

from module1.foo1 import ClassName

相关问题 更多 >