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
1# Program to read a text file and print its contents23filename = input("Enter filename: ")45try: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.
After this program
If the idea is still fuzzy, read Day 14: File Handling in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 20 file handling programs, or see every topic on Python exercises.