python使用相对路径导入包时需要先获取当前目录:dir = os.path.dirname(os.path.abspath("__file__")) 或者 dir = os.getcwd()
然后添加到 sys.path:
sys.path.append(dir)
sys.path
是一个列表,包含了 Python 解释器在查找模块时会搜索的目录。
import sys
import os
root_dir = os.path.dirname(os.path.abspath("__file__"))
# root_dir = os.getcwd()
sys.path.append(root_dir)
注意:如果是在python文件中,以下都是可用的
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(os.path.dirname(os.path.abspath(“__file__”)))
但是,__file__
在 Jupyter Notebook 中并不直接可用,要使用 "__file__"