File Content Reader

Write a Python program that prompts the user to enter a file name and then prints the contents of that file. Implement exception handling for scenarios like the file not being found or the user not having permission to read the file.

Example 1:

Input: filename = "test_file.txt" (file contains the string "Hello, World!") 
Output: "Hello, World!"

Example 2:

Input: filename = "non_existent.txt" 
Output: "Error: File does not exist."

Use the built-in open() function to open the file and read() to get the contents. Be sure to wrap the operation in a try/except block to handle potential exceptions.

def read_file_content(filename):
    try:
        with open(filename, 'r') as f:
            content = f.read()
            return content
    except FileNotFoundError:
        return "Error: File does not exist."
    except PermissionError:
        return "Error: You do not have permission to read the file."

print(read_file_content("test_file.txt"))
print(read_file_content("non_existent.txt"))

 

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!