-1

Hello i am new to python programming. I am self learning by doing a project.

the code below is working fine, but i want to catch the exception if the condition is FALSE. i already have a statement to print if the directory is not there; and continue. I know i can make this code work by nesting the if statement.

but i dont want to do. i want to proceed to next line of code. when i run this as it is, i will get an error if the directory is missing.

import os
goToDir = open("URPsetup.dat","r")
goToDirPath = goToDir.read()

if (os.path.exists(goToDirPath))== True:
os.chdir(goToDirPath)
else: print("directory not found, please check file URPsetup.dat")

goToConfig = open("utility.dat", "r")
print(goToConfig.read())

i get this error message when the directory is not there. What i mean here is that, the directory i supplied in "URPsetup.dat" was incorrect. I did this on purpose to see if the code will stop at the else statement above. it will print the else statement, and continue on to show the error message below. how do i catch this error and stop?

directory not found, please check file URPsetup.dat
Traceback (most recent call last):
File "C:/Users/R82436/PycharmProjects/URP2017/prototype.py", line 9, in     <module>
goToConfig = open("utility.dat", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'utility.dat'
directory not found, please check file URPsetup.dat

Process finished with exit code 1
Dean
  • 65
  • 1
  • 8
  • If the file doesn't exist, how do you want to "proceed on"? – AetherUnbound Jun 23 '17 at 05:44
  • Just show the message that the directory is wrong. I supplied an incorrect directory on purpose. If I supplied a correct directory it will work – Dean Jun 23 '17 at 05:53
  • You say "i will get an error", but you don't say what error, or what part of your code is causing it. Please edit the question to supply the full traceback of any exception you're getting. It will identify what's going wrong and maybe then we can help you. Without that information, we can only guess what the issue you're having is. – Blckknght Jun 23 '17 at 06:00
  • i have updated the question. i know what is causing the error message. but what i really want to know is how do i catch it and stop at the else statement. is it possible? – Dean Jun 23 '17 at 06:10

1 Answers1

-2

I GUESS you're looking for this:

import sys
.
.
else: 
    print("directory not found, please check file URPsetup.dat")
    sys.exit()
.
.

OR this will do just fine too:

# No need to import sys
.
.
else: 
    print("directory not found, please check file URPsetup.dat")
    raise SystemExit(0)
.
.

That will do the trick ;)

And try to explain your problem properly next time, You aren't completely clear on what is it exactly that you want to do.