Blakester Blakester - 20 days ago 7
Python Question

How to keep asking the user for a file

New programmer here, and well let me start off with the code I have.

try:
f = input("Please type in the path to your file and press 'Enter'")
file = open(f,'r')
except FileNotFoundError:
f = input("File not found please try again.")


What I'm trying to accomplish, is if the user enters a wrong file, to keep asking the user to try again. Maybe I shouldn't be using try/except?

Answer

Embed the statement inside a while loop. break if file is opened successfully.

while True:
    try:
        f = input("Please type in the path to your file and press 'Enter'")
        file = open(f, 'r')
        break
    except FileNotFoundError:
        print('File not found')

NOTE: You may need to handle other exceptions like IOError (even though, there is a file, you may not possible to open it - because of permsssion, wrong file type, ..)

Comments