[英]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.