簡體   English   中英

如何使用相對路徑導入其他文件到執行文件而不是python命令路徑?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM