Python
Python

 

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:

  1. 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.
  2. Open the File: The open() function is used to open the file in ‘read’ mode (‘r’). This opens the file for reading only.
  3. 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.
  4. Displaying Content: The content of the file is then printed on the console using the print() function.
  5. 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:

  1. Create a text file (e.g., “example.txt”) and add some content to it.
  2. Save the Python program in a file with a .py extension (e.g., read_file.py).
  3. Ensure that the Python file and the text file are in the same directory (or update the file_name variable to the correct path).
  4. Run the Python program using the following command in your terminal or command prompt: python read_file.py
  5. The contents of the file will be displayed in the console.
© 2024 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)