3

I'm trying to validate a list of input directories and want the script to raise errors if the directories do not exist. I don't believe if-not will work here since if these folders do not exist (with the required input files [I have another validation for this]) then the script cannot run.

folder1 = "d:\\temp\\exists"
folder2 = "d:\\temp\\notexists"
list = [folder1, folder2]
list #gives ['d:\\temp\\exists', 'd:\\temp\\notexists']

for l in list:
    try:
        os.path.exists(l)
        print("{0} folder exists...".format(l))
    except FileNotFoundError:
        print("{0} folder does not exist!".format(l))

os.path.exists correctly identifies folder2 as not existing, but does not raise an exception:

True
d:\temp\exists folder exists...
False
d:\temp\notexists folder exists...
Clickinaway
  • 177
  • 1
  • 3
  • 9
  • 1
    You can reach that code without errors, so the code will not go to the exception block. The path.exists gives a boolean that tells you if a path exists, so even when it does not – chatax Feb 20 '20 at 16:42
  • Calling ``os.path.exists`` does not raise any errors if the file does not exist (it just returns ``False``). Why do you think ``FileNotFoundError`` would be raised in your code? – MisterMiyagi Feb 20 '20 at 17:06
  • You could raise a generic exception like in [this answer](https://stackoverflow.com/a/29954408/11764049) – Aelius Apr 29 '21 at 13:58

2 Answers2

4

If you want the code to stop and raise an error:

for l in list: 
    if os.path.exists(l): 
        print("{0} folder exists...".format(l))
   else:
      raise FileNotFoundError("{0} folder does not exist!".format(l))
chatax
  • 990
  • 3
  • 17
0

if...else block should do the trick

folder1 = "d:\\temp\\exists"
folder2 = "d:\\temp\\notexists"
list = [folder1, folder2]
list #gives ['d:\\temp\\exists', 'd:\\temp\\notexists']

for l in list:
    if os.path.exists(l)
        print("{0} folder exists...".format(l))
    else:
        print("{0} folder does not exist!".format(l))