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)

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()

Thanks alot! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.