Which Python condition that check "file A or B or both exist"

Question:

May I ask which condition I should use to check the files A or B or both exist then execute the expression A or B or Both?

if or while or try...

enter image description here
Thanks

Asked By: David L

||

Answers:

Try with os.path.exists

Remember to import os

Answered By: alejandroklever

You can use os.path.isfile to check if a file exists. Now you can do the same for multiple files in a similar way…

import os.path

fname_A = fr'./file_A.txt' #<============ File A
fname_B = fr'./file_B.txt' #<============ File B

if os.path.isfile(fname_A):
    if os.path.isfile(fname_B):
        print('A and B exist')
    else:
        print('only A exists')
elif os.path.isfile(fname_B):
    print('only B exists')
else:
    print('Neither A nor B exists')
Answered By: learner

Try break it down to one path at a time e.g into two functions that does something if A exists and something if B exists. Then it is fairly easy to do them both if A and B exists.

If you want to get assistance with some code-specific issues please write what you have tried, why it didn’t work (i.e what happend that you did not expect?) or where you get stuck.

Answered By: CutePoison

I would test if they both exist first, something like

if fileA exists:
  if fileB exists:
   both_exist = True
  else:
   file_A_exists = True
   
elif fileB exists:
  file_B_exists = True

Of course that code doesn’t actually work, but it gives an idea of where you would want to check for files existing. A good command you can use to check if a file exists is os.path.exists(fileA) but you will need to import os.

And then, if you want to execute the code, all you have to do is run the correct command next to the variable line, so:

Line 3-5:

  both_exist = True
  os.system('python fileA.py')
  os.system('python fileB.py')

That would be for python, and you’d have to import os to actually run the os.system(‘python’) command.

Answered By: donut28