0

Hey! Just wondering how you make the code keep asking for a correct file input until a correct file is inputted, rather than just exiting the program when incorrect?

f = input("Enter a file name: ")

try:
   infile = open(f, "r")

except:
   print("File not found:", f)

text = infile.read()
print(text)
2
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by TeaAnyOne
0

This will do it,try not to use bare except.
except (<some error>, <another error>)

You can also use except IOError as error: print error
This will give you an error message with specific information about the caught exception.

def file_exists():
    while True:
        file_name = input("Enter a file name: ")
        try:
            with open(file_name) as a_file:
                return a_file.read()
        except IOError:
            print('No file with name: <{}> found'.format(file_name))
            pass

print file_exists()

Edited by snippsat

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.