Search code examples
pythonloopswhile-looptry-catchexcept

Try and Except inside of a While Loop - Opening files


I am trying to prompt the user for a file to read, and if the file is not found in the directory, it will print a message and then re-prompt the user. For Error Handling I try to use an Try and Except statement and i try to loop it with a while loop. Help please why doesn't this work!

while True:

    try:
        input_file = input('Enter the name of the Input File: ' )
        ifile = (input_file, 'r' )
        continue

    except:
        print('File not found. Try again.')

Solution

  • It would make more sense to check with os.path.isfile

    import os
    
    while True:
    
        input_file = input('Enter the name of the Input File: ')
        if not os.path.isfile(input_file):
            print('File not found. Try again.')
            continue
        break
    
    print('File found!')