Home > Software design >  Check if a file exist in appdata without adding the full path in the python code
Check if a file exist in appdata without adding the full path in the python code

Time:11-25

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")
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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

CodePudding user response:

%% is mostly used in windows and batch scripts. This will be another way to do so, where you create the path till java.exe from the environmental variable APPDATA.

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