[英]How to import other file using relative path to executed file not python command path?
我的文件夾樹:
./
├── README.MD
├── basic
│ └── thresh.py
├── images
│ └── figure.jpg
└── utils
├── util.py
└── util.pyc
我想在util.py
中導入thresh.py
:
import sys
sys.path.append('../utils')
import util
當我在basic
文件夾中運行命令$ python thresh.py
時,沒問題。 但是在最上面的文件夾中運行$ python ./basic/thresh.py
,我會得到錯誤:
導入錯誤:沒有名為 util 的模塊
那么如何讓$ python ./basic/thresh.py
和$ python thresh.py
都可以通過給定文件的相對路徑來導入文件,而不管 python 命令路徑如何?
您可以獲得正在執行的腳本的絕對路徑(還有其他變體也使用__file__
,但這應該有效)
import os
wk_dir = os.path.dirname(os.path.realpath('__file__'))
print( wk_dir )
然后得到你的目錄,例如
import sys
sys.path.append(wk_dir+'/../utils')
PS:您可能需要使用__file__
而不是'__file__'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.