alexia231
alexia231

Reputation: 41

Opening files using try-except

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.

Upvotes: 0

Views: 662

Answers (1)

Mahmoud Elshahat
Mahmoud Elshahat

Reputation: 1959

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

Upvotes: 1

Related Questions