Python Read Files – Read Text Files in Python

Introduction

Reading files is one of the most common tasks in programming. Whether you are developing a web application, processing data, generating reports, or managing user information, you often need to read data stored in files. Python provides simple and powerful built-in functions that make reading files easy and efficient.

Python supports reading various file types, including text files, CSV files, JSON files, and binary files.

What is Python Read Files?

Python Read Files refers to the process of retrieving data from a file and using it within a Python program. Python provides several methods for reading file content depending on your requirements.

To read a file, Python first opens it using the open() function and then uses methods such as:

  • read()
  • readline()
  • readlines()
  • File iteration using loops

Syntax

The basic syntax for reading a file is:


file = open("filename.txt", "r")
content = file.read()
print(content)
file.close()

Explanation

  • open() opens the file.
  • “filename.txt” is the file name.
  • “r” means read mode.
  • read() reads the file content.
  • close() closes the file.

Understanding Read Mode

The “r” mode stands for read mode.


file = open("data.txt", "r")

Features:

  • Opens an existing file.
  • Does not modify file content.
  • Raises an error if the file does not exist.

Example:


file = open("students.txt", "r")
print(file.read())
file.close()

Output:

John
Alice
Bob

Reading an Entire File Using read()

The read() method reads the entire content of a file.

Example:

Suppose the file contains:


Python
Java
C++

Code:


file = open("languages.txt", "r")
content = file.read()
print(content)
file.close()

Output:

Python
Java
C++

Reading a Specific Number of Characters

The read() method can also accept a number.

Syntax:


file.read(number)

Example:


file = open("data.txt", "r")
print(file.read(5))
file.close()

Output:

Hello

Only the first 5 characters are read.

Reading One Line Using readline()

The readline() method reads a single line from the file.

Example:

File Content:


Python
Java
C++

Code:


file = open("languages.txt", "r")
print(file.readline())
file.close()

Output:

Python

Reading Multiple Lines Using readline()

You can call readline() multiple times.


file = open("languages.txt", "r")
print(file.readline())
print(file.readline())
file.close()

Output:

Python
Java

Each call reads the next line.

Reading All Lines Using readlines()

The readlines() method returns all lines as a list.

Example:


file = open("languages.txt", "r")
lines = file.readlines()
print(lines)
file.close()

Output:

[‘Python\n’, ‘Java\n’, ‘C++’]

Notice that each line is stored as a separate element in the list.

Reading Files Using a Loop

A common and memory-efficient way to read files is using a loop.

Example:


file = open("languages.txt", "r")
for line in file:
    print(line)
file.close()

Output:

Python
Java
C++

This approach is recommended for large files.

Using the with Statement

Python provides a better way to handle files using the with statement.

Example:


with open("languages.txt", "r") as file:
    print(file.read())

Output:

Python
Java
C++

Advantages:

  • Automatically closes the file.
  • Cleaner code.
  • Better resource management.

Reading Large Files Efficiently

When working with large files, avoid using read() because it loads the entire file into memory.

Instead:


with open("largefile.txt", "r") as file:
    for line in file:
        print(line)

Benefits:

  • Lower memory usage
  • Better performance
  • Suitable for large datasets

Reading Binary Files

Binary files contain non-text data such as:

  • Images
  • Videos
  • PDFs
  • Audio files

Use rb mode.

Example:


file = open("image.jpg", "rb")
data = file.read()
file.close()

Output:

Binary data is loaded into memory.

Example

The following example reads a student file.

File Content:


John
Alice
Robert
David

Program:


with open("students.txt", "r") as file:
    content = file.read()
print(content)

Output:

John
Alice
Robert
David

This is one of the most common examples of file reading.

Real-life Example

Imagine you are building an online institute management system.

Student names are stored in a file called students.txt.

File Content:


Amit
Rahul
Priya
Neha

Program:


with open("students.txt", "r") as file:
    for student in file:
        print(student.strip())

Output:

Amit
Rahul
Priya
Neha

Why Is This Useful?

Instead of manually entering student names every time, the program can retrieve information directly from stored files.

Common Mistakes

1. Forgetting to Close the File

Incorrect:


file = open("data.txt", "r")
print(file.read())

The file remains open.

Correct:


file = open("data.txt", "r")
print(file.read())
file.close()

Or:


with open("data.txt", "r") as file:
    print(file.read())

2. Opening a Non-Existing File

Incorrect:


file = open("unknown.txt", "r")

Output:

FileNotFoundError

Correct:


import os
if os.path.exists("unknown.txt"):
    file = open("unknown.txt", "r")

3. Using Write Mode Instead of Read Mode

Incorrect:


file = open("data.txt", "w")

This can erase existing data.

Correct:


file = open("data.txt", "r")

4. Reading Huge Files Using read()

Incorrect:


content = file.read()

For large files this consumes a lot of memory.

Correct:

for line in file:


    print(line)

5. Not Handling Exceptions

Incorrect:


file = open("data.txt", "r")

Correct:


try:
    with open("data.txt", "r") as file:
        print(file.read())

except FileNotFoundError:


 print("File not found")

Conclusion

Python provides several powerful ways to read files, making it easy to work with stored data. Methods such as read(), readline(), and readlines() allow developers to retrieve file content based on their specific needs. For larger files, reading line by line is the most efficient approach.

Python File Read – Interview Questions

Q 1: How do you read a file in Python?
Ans: Using the read(), readline(), or readlines() methods.
Q 2: What does read() do?
Ans: It reads the entire content of the file as a string.
Q 3: What does readline() do?
Ans: It reads one line of the file at a time.
Q 4: What does readlines() return?
Ans: A list containing all lines of the file.
Q 5: Can you iterate over a file object?
Ans: Yes, using a for loop to read line by line.

Python File Read – Objective Questions (MCQs)

Q1. Which mode is used to read a file in Python?






Q2. Which method is used to write data to a file in Python?






Q3. What does the following code do?

with open("file.txt", "r") as f:
data = f.read()






Q4. Which method is used to read a single line from a file?






Q5. What is the purpose of the "a" mode in file handling?






Related Python Tutorials