Here is the directory structure:
这是目录结构:
parent_dir/
foo_dir/
foo.py
bar_dir/
bar.py
How do I import bar.py into foo.py?
如何将bar.py导入foo.py?
2 个解决方案
#1
30
If all occurring directories are Python packages, i.e. they all contain __init__.py
, then you can use
如果所有发生的目录都是Python包,即它们都包含__init__.py,那么您可以使用
from ..bar_dir import bar
If the directories aren't Python packages, you can do this by messing around with sys.path
, but you shouldn't.
如果这些目录不是Python包,你可以通过搞乱sys.path来实现,但你不应该这样做。
#2
12
You can use the sys
and os
modules for generalized imports. In foo.py
start with the lines
您可以使用sys和os模块进行通用导入。在foo.py中以行开头
import sys
import os
sys.path.append(os.path.abspath('../bar_dir'))
import bar
#1
30
If all occurring directories are Python packages, i.e. they all contain __init__.py
, then you can use
如果所有发生的目录都是Python包,即它们都包含__init__.py,那么您可以使用
from ..bar_dir import bar
If the directories aren't Python packages, you can do this by messing around with sys.path
, but you shouldn't.
如果这些目录不是Python包,你可以通过搞乱sys.path来实现,但你不应该这样做。
#2
12
You can use the sys
and os
modules for generalized imports. In foo.py
start with the lines
您可以使用sys和os模块进行通用导入。在foo.py中以行开头
import sys
import os
sys.path.append(os.path.abspath('../bar_dir'))
import bar