在 python 代码中检查文件是否存在于 appdata 中而不添加完整路径
Check if a file exist in appdata without adding the full path in the python code
如何在不在 python 代码中添加完整路径的情况下使用环境变量检查 appdata 中是否存在文件?我已经添加了 %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")
尝试使用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")
%%
主要用于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")
如何在不在 python 代码中添加完整路径的情况下使用环境变量检查 appdata 中是否存在文件?我已经添加了 %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")
尝试使用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")
%%
主要用于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")