检查appdata中是不是存在文件而不在python代码中添加完整路径

Posted

技术标签:

【中文标题】检查appdata中是不是存在文件而不在python代码中添加完整路径【英文标题】:Check if a file exist in appdata without adding the full path in the python code检查appdata中是否存在文件而不在python代码中添加完整路径 【发布时间】:2022-01-03 15:08:11 【问题描述】:

如何使用环境变量检查 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")

【问题讨论】:

【参考方案1】:

尝试使用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")

【讨论】:

【参考方案2】:

%% 主要用于 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")

【讨论】:

以上是关于检查appdata中是不是存在文件而不在python代码中添加完整路径的主要内容,如果未能解决你的问题,请参考以下文章