Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

os.path.exists returns false but not raising exception in try/except block

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...
like image 300
Clickinaway Avatar asked Feb 02 '26 02:02

Clickinaway


1 Answers

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))
like image 59
chatax Avatar answered Feb 04 '26 16:02

chatax



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!