Search code examples
pythonpython-3.xexceptionexcept

what is an exception handler for


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)

Solution

  • 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