Introduction
In Python, file handling allows us to interact with files and perform operations such as reading and writing data to files.
One of the most common tasks is to read the contents of a file and display it. Python provides various built-in functions and methods
to handle files efficiently. In this program, we will learn how to read a file and display its content using Python.
Objective:
The objective of this program is to read a text file and display its content on the console. This will help you understand how
to work with files, handle file paths, and read the content line by line.
Python Code
# Program to read and display the contents of a file
# Open the file in read mode
file_name = "example.txt" # Specify the file name
try:
with open(file_name, 'r') as file: # Open the file in read mode
content = file.read() # Read the entire content of the file
print("Contents of the file:")
print(content) # Display the file content
except FileNotFoundError:
print(f"Error: The file '{file_name}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
Program Explanation
This program demonstrates how to open a file, read its content, and display it on the console. Here’s a breakdown of how it works:
- File Name: The file name is specified in the
file_name
variable (in this case, “example.txt”). You can replace it with the name of the file you wish to read. - Open the File: The
open()
function is used to open the file in ‘read’ mode (‘r’). This opens the file for reading only. - Reading the File: The
file.read()
method is used to read the entire content of the file. This reads the content as a single string. - Displaying Content: The content of the file is then printed on the console using the
print()
function. - Error Handling: The program includes a
try-except
block to handle any errors, such as the file not being found or other issues during the file operations.
How to Run the Program
To run this program, follow these steps:
- Create a text file (e.g., “example.txt”) and add some content to it.
- Save the Python program in a file with a .py extension (e.g.,
read_file.py
). - Ensure that the Python file and the text file are in the same directory (or update the
file_name
variable to the correct path). - Run the Python program using the following command in your terminal or command prompt:
python read_file.py
- The contents of the file will be displayed in the console.