Python Program to Read a File

Introduction

Reading files is a common task in Python programming, especially when dealing with data processing, configuration files, or logging. Python provides built-in functions to easily read the contents of a file. This tutorial will guide you through creating a Python program that reads the contents of a file and displays it.

Example:

  • File Content (example.txt):
    Hello, World! Welcome to Python file handling. 
  • Program Output:
    Hello, World! Welcome to Python file handling. 

Problem Statement

Create a Python program that:

  • Opens a file for reading.
  • Reads the content of the file.
  • Displays the content of the file line by line.

Solution Steps

  1. Specify the File Name: Provide the name of the file to be read.
  2. Open the File: Use the open() function to open the file in read mode.
  3. Read the File Content: Use the read() or readlines() method to read the file’s content.
  4. Display the File Content: Print the content of the file to the console.
  5. Close the File: Ensure the file is properly closed after reading.

Python Program

# Python Program to Read a File # Author: https://www.rameshfadatare.com/ # Step 1: Specify the file name file_name = "example.txt" # Step 2: Open the file in read mode try: with open(file_name, "r") as file: # Step 3: Read the content of the file content = file.read() # Step 4: Display the content of the file print("File Content:\n") print(content) except FileNotFoundError: print(f"The file '{file_name}' does not exist.") except IOError: print(f"An error occurred while reading the file '{file_name}'.") 

Explanation

Step 1: Specify the File Name

  • The variable file_name is assigned the name of the file to be read. Make sure the file exists in the same directory as the Python script, or provide the full path to the file.

Step 2: Open the File in Read Mode

  • The open() function is used to open the file in read mode ("r"). The with statement ensures that the file is automatically closed after reading, even if an error occurs.

Step 3: Read the Content of the File

  • The read() method is used to read the entire content of the file into the variable content.

Step 4: Display the Content of the File

  • The print() function is used to display the file’s content.

Step 5: Handle Exceptions

  • The program includes exception handling using try-except blocks to catch and handle errors such as FileNotFoundError if the file does not exist, or IOError for general input/output errors.

Output Example

Example Output (Assuming example.txt contains the text provided):

File Content: Hello, World! Welcome to Python file handling. 

Additional Examples

Example 1: Reading a File Line by Line

# Reading a file line by line file_name = "example.txt" try: with open(file_name, "r") as file: print("File Content Line by Line:\n") for line in file: print(line, end="") # end="" avoids adding extra newlines except FileNotFoundError: print(f"The file '{file_name}' does not exist.") except IOError: print(f"An error occurred while reading the file '{file_name}'.") 

Output:

File Content Line by Line: Hello, World! Welcome to Python file handling. 

Example 2: Using readlines() to Read All Lines at Once

# Reading all lines at once and processing them file_name = "example.txt" try: with open(file_name, "r") as file: lines = file.readlines() # Reads all lines into a list print("Processed File Content:\n") for line in lines: print(line.strip()) # strip() removes leading/trailing whitespace except FileNotFoundError: print(f"The file '{file_name}' does not exist.") except IOError: print(f"An error occurred while reading the file '{file_name}'.") 

Output:

Processed File Content: Hello, World! Welcome to Python file handling. 

Example 3: Handling Large Files with readline()

# Reading large files efficiently with readline() file_name = "large_file.txt" try: with open(file_name, "r") as file: print("Reading large file line by line:\n") while True: line = file.readline() if not line: break print(line, end="") except FileNotFoundError: print(f"The file '{file_name}' does not exist.") except IOError: print(f"An error occurred while reading the file '{file_name}'.") 

Output: (Output will vary based on the content of large_file.txt)

Conclusion

This Python program demonstrates how to read a file’s content and display it using the open() function and various file reading methods like read(), readline(), and readlines(). The program also includes exception handling to manage errors that may occur during file operations, making it robust for real-world applications. Understanding file handling is essential for managing data in Python, especially in tasks involving data processing, logging, or configuration management.

Leave a Comment

Scroll to Top