Question: open\_file(): This function takes no parameters, then uses the try-except format to prompt for a filename, open the data file and return the file pointer if successful. Your function should be able to catch the error and print the error message if it fails to open; and then reprompt. It will reprompt

I have written this code but not sure if it is correct and meets the requirements mentioned above. Can anyone please help me?

```
def open_file():
    try:
        fp = open(file, 'r')
        return fp
    except FileNotFoundError:
        fp = open('congress.txt','r')

file = open('congress.txt', 'r')
for line in file:
    print(line)

```

Answer: 
```
def open_file(max_tries=20):
    tries = 0
    fp = None    # We don't have that yet
    while not tries or not fp:  # While the file is not loaded (or we haven't tried)
        tries += 1 # One more try
        try:       # Try to load it
            fp = open(input("enter a filename : "))
        except FileNotFoundError:   # Oops  
            print("file not found")  # We should tell the user about that
            if tries > max_tries: break  # We shouldn't go into an infinite loop
        except IsADirectoryError:   # Oops  
            print("file is a directory")  # We should tell the user about that
            if tries > max_tries: break  # We shouldn't go into an infinite loop
    else: return fp      # When you got the fp, return it
    pass # If you didn't get it run the code here (maybe raise an exception)
    # If you don't raise an exception, it will return None

```
I reworked it a bit, but this will do what you want it to do.

```
def open_file():
    try:
        file_name = input("What is the filename? ")
        with open(file_name) as fp:
            new_doc = fp.read()
        return new_doc
    except FileNotFoundError:
        print("File not found")
        new_doc = open_file()
        return new_doc

file = open_file()
print(file)

```