Read File

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

BeginnerTopic: File Handling Programs
Back

Python Read File Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# 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...

Understanding Read File

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

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents