0

I'm trying to write a function that allows reading a file, and if the file we want them to read doesn't exist, I want other functions and other code writing in the code to stop.

def readfile():
    ok = False
    while not ok:
        try:
            fnR = input()
            f = open(fnR,"r")
            readcontent = f.read()
            ok = True
        except:
            print("file not found")
            slc = int(input("to exit type '0' \n to try again type '1' "))
            if slc == 0:
                break
            elif slc == 1:
                ok = False

readfile()


x = 15+10
print(x)

i dont want to print x or calculate x i want to stop the entire code below the "readfile()" functions

3 Answers3

1

What you want to do is exit the script if a file could not be read (you can use raise SystemExit - this will exit the script and send the appropriate exit code to the OS. You can refer to the top answer on this question.

kiwibg
  • 334
  • 2
  • 9
  • 1
    If you are aware of such a detailed and highly voted answer, why did you answer this question instead of flagging as a duplicate? – Tomerikoo Jan 03 '23 at 14:42
  • @Tomerikoo fair point - it would have been better to put any additional explanations as a comment rather than an answer – kiwibg Jan 03 '23 at 14:51
0

To stop a python program, you can use the exit() function.

        if slc == 0:
            exit()
        elif slc == 1:
            ok = False
Itération 122442
  • 2,644
  • 2
  • 27
  • 73
  • when i try this code in "except:" its work but it doesnt work when i try this in "try:" –  Jan 03 '23 at 19:42
0

replace break with exit() - it exits the program instead of exiting the loop

Pythoneer
  • 319
  • 1
  • 16