0

I need to create a function called open_file(message) that prompts the user to enter the name of the file repeatedly, until a proper name is opened. If no name is entered (an empty string) the default file needs to be a file called pass.txt.

I have tried using a while loop with the try and except method. I am confused on how to define the function.

def open_file(message):
    '''Put your docstring here'''

    filename = input("Enter the name of the file: ")
    while True:
        if filename == "" or filename == " ":
            filename = "pass.txt"
            fileopen = open("pass.txt", "r")
            break
        else:
            try:
                fileopen = open(filename, "r")
                break
            except FileNotFoundError:
                print("file not found, try again.")
                print(filename)  
    return fileopen

Expected result is to open the user-entered file name or to open the default file while repeatedly prompting for the correct filename if the entered file name cannot be found or opened.

martineau
  • 119,623
  • 25
  • 170
  • 301
alexia231
  • 41
  • 1
  • 5
  • Your `pass.txt` default case will clearly go into an infinite loop. Better to just just assign to `filename`, then fall through, changing the `else` code (remove the `else` and de-indent) so that it is always executed. And move the prompt code for `filename` to the top of the loop of course. As it is now, it will never prompt more than once. – Tom Karzes Apr 05 '19 at 23:16
  • See answer(s) to [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). Possible duplicate... – martineau Apr 05 '19 at 23:28

1 Answers1

1

Move your input statement inside while loop

Edit: remove function parameter "message" if you don't need it

def open_file():
    '''Put your docstring here'''

    while True:
        filename = input("Enter the name of the file: ")
        if filename == "" or filename == " ":
            filename = "pass.txt"
            fileopen = open("pass.txt", "r")
            break
        else:
            try:
                fileopen = open(filename, "r")
                break
            except FileNotFoundError:
                print("file not found, try again.")
                print(filename)  
    return fileopen
Mahmoud Elshahat
  • 1,873
  • 10
  • 24