如何使用環境變數檢查 appdata 中是否存在檔案而不在 python 代碼中添加完整路徑?我添加了 %APPDATA% 但代碼不能使用環境變數
import os
PATH = '%APPDATA%\\java.exe'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print("File exists and is readable")
else:
print("Either the file is missing or not readable")
uj5u.com熱心網友回復:
嘗試使用os.path.expandvars:
import os
PATH = os.path.expandvars('%APPDATA%\\java.exe') # <- HERE
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print("File exists and is readable")
else:
print("Either the file is missing or not readable")
uj5u.com熱心網友回復:
%%主要用于 windows 和批處理腳本。這將是另一種方法,您可以在其中從環境變數 APPDATA 創建直到 java.exe 的路徑。
import os
PATH = os.path.join(os.getenv('APPDATA'), 'java.exe')
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
print("File exists and is readable")
else:
print("Either the file is missing or not readable")
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/365666.html
上一篇:當sql_error_code=28000(主機沒有pg_hba.conf條目)時,如何正確設定HerokuNode.js與Heroku-Postgres的連接
