[英]Need to understand how to import module in python from one directory up
我有这样的结构
pkg1
__init__.py
file_1.py
file2.py
pkg2
test_1.py
__init__.py
我有一个像上面这样的结构。 我在test_1.py
中有一个代码试图加载file_1.py
#test_1.py
from pkg1 import file_1
# from .. import file_1
两种说法都不起作用。 如何从 pfg1 导入 file_1
python 程序可以通过直接向 sys.path 添加元素来修改其路径。 import sys 然后您可以在运行时添加到系统路径:
import sys
sys.path.insert(0, 'path/to/your/py_file')
import py_file
或者你可以这样做:
import sys
import os
base_dir = os.path.dirname(__file__) or '.'
# Insert the package_dir_a directory at the front of the path.
package_dir_a = os.path.join(base_dir, 'package_dir_a')
sys.path.insert(0, package_dir_a)
import py_file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.