File Opening with Exception Handling

Write a Python function that accepts a filename as input and attempts to open it. If the file does not exist, return the string “Error: File does not exist”.

Example 1:

Input: "existing_file.txt"

Output: "File opened successfully"

Example 2:

Input: "non_existent_file.txt"

Output: "Error: File does not exist"

Use try-except block to handle FileNotFoundError.

def open_file(filename):
    try:
        with open(filename, 'r') as f:
            return "File opened successfully"
    except FileNotFoundError:
        return "Error: File does not exist"

print(open_file("existing_file.txt"))  # Output: "File opened successfully"
print(open_file("non_existent_file.txt"))  # Output: "Error: File does not exist"

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!