Check if a file exist in appdata without adding the full path in the python code

Advertisements

How i can check if a file exist in appdata using a environment variable without adding the full path in the python code ?? i have added %APPDATA% but the code is not working with a environment variable

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")

>Solution :

Try to use 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")

Leave a ReplyCancel reply