[英]How to import python script from a different directory using relative paths?
[英]Relative paths break when executing Python script from Windows batch?
如果我直接從它所在的目錄中執行它,我的Python腳本就可以正常工作。但是如果我退出該目錄並嘗試從其他地方執行它(不更改任何代碼或文件位置),所有相對路徑都會中斷得到一個FileNotFoundError
。
該腳本位於./scripts/bin/my_script.py
。 有一個名為./scripts/bin/data/
的目錄。 就像我說的那樣,只要我從同一個目錄執行它就完全可以工作......所以我很困惑。
成功執行 ( 在 ./scripts/bin/
): python my_script.py
執行失敗 ( 在 ./scripts/
): python bin/my_script.py
和python ./bin/my_script.py
失敗消息:
Traceback (most recent call last):
File "./bin/my_script.py", line 87, in <module>
run()
File "./bin/my_script.py", line 61, in run
load_data()
File "C:\Users\XXXX\Desktop\scripts\bin\tables.py", line 12, in load_data
DATA = read_file("data/my_data.txt")
File "C:\Users\XXXX\Desktop\scripts\bin\fileutil.py", line 5, in read_file
with open(filename, "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'data/my_data.txt'
相關的Python代碼 :
def read_file(filename):
with open(filename, "r") as file:
lines = [line.strip() for line in file]
return [line for line in lines if len(line) == 0 or line[0] != "#"]
def load_data():
global DATA
DATA = read_file("data/my_data.txt")
是的,這是合乎邏輯的。 這些文件是相對於您的工作目錄的。 您可以通過從其他目錄運行腳本來更改它。 你可以做的是在運行時獲取你正在運行的腳本的目錄並從中構建。
import os
def read_file(filename):
#get the directory of the current running script. "__file__" is its full path
path, fl = os.path.split(os.path.realpath(__file__))
#use path to create the fully classified path to your data
full_path = os.path.join(path, filename)
with open(full_path, "r") as file:
#etc
您的資源文件與您的腳本相關。 這沒關系,但你需要使用
os.path.realpath(__file__)
要么
os.path.dirname(sys.argv[0])
獲取腳本所在的目錄。 然后使用os.path.join()
或其他函數生成資源文件的路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.