Read File in Python

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

BeginnerFile Handling ProgramsExample 1 of 20
read-file.py
Run in browser
1# Program to read a text file and print its contents
2
3filename = input("Enter filename: ")
4
5try:
6 with open(filename, "r", encoding="utf-8") as f:
7 contents = f.read()
8 print("File contents:")
9 print(contents)
10except FileNotFoundError:
11 print("File not found.")

Output

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

What's going on

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