Read File

Read and print the contents of a text file using a context manager.

PythonBeginner
Python
# Program to read a text file and print its contents

filename = input("Enter filename: ")

try:
    with open(filename, "r", encoding="utf-8") as f:
        contents = f.read()
        print("File contents:")
        print(contents)
except FileNotFoundError:
    print("File not found.")

Output

Enter filename: sample.txt
File contents:
...file content here...

Uses 'with open(..., "r")' to safely read a file and automatically close it, with basic FileNotFoundError handling.