-4

I have a script which wants to load integers from a text file. If the file does not exist I want the user to be able to browse for a different file (or the same file in a different location, I have UI implementation for that). What I don't get is what the purpose of Exception handling, or catching exceptions is. From what I have read it seems to be something you can use to log errors, but if an input is needed catching the exception won't fix that. I am wondering if a while loop in the except block is the approach to use (or don't use the try/except for loading a file)?

with open(myfile, 'r') as f:
    try:
        with open(myfile, 'r') as f:
            contents = f.read()
        print("From text file : ", contents)
    except FileNotFoundError as Ex:
        print(Ex)
Albin Sidås
  • 321
  • 2
  • 10
Windy71
  • 851
  • 1
  • 9
  • 30
  • 2
    *If* you do not want to handle exceptions but instead you want the program to crash you are free to do so, **your** decision. But there are an infinite amount of situations where you explicitly do not want to crash the program but instead handle it gracefully. – luk2302 Dec 14 '21 at 08:51
  • 1
    The `except` part is where you would implement the part _If the file does not exist I want the user to be able to browse for a different file (or the same file in a different location_ – buran Dec 14 '21 at 08:55
  • Thank you buran. I am self taught and couldn't find examples online of anyone using the except block for anything other than logging an error or printing the exception. – Windy71 Dec 14 '21 at 08:56

1 Answers1

1

You need to use to while loop and use a variable to verify in the file is found or not, if not found, set in the input the name of the file and read again and so on:

filenotfound = True
file_path = myfile
while filenotfound:
    try:
        with open(file_path, 'r') as f:
            contents = f.read()
        print("From text file : ", contents)
        filenotfound = False
    except FileNotFoundError as Ex:
        file_path = str(input())
        filenotfound = True
alphaBetaGamma
  • 653
  • 6
  • 19