February 8, 2025

Readlines in Python

The readlines() method in Python is used to read all the lines of a file and return them as a list of strings. Each string in the list represents a single line from the file, including the newline character at the end of each line. This method is useful when you need to process or manipulate the lines of a file individually.

1. Syntax

file.readlines(hint=-1)

Where:

  • file is the file object obtained by opening a file using open().
  • hint is an optional parameter that specifies the approximate number of bytes to read. If omitted or set to -1, the entire file is read.

2. Examples

2.1 Reading All Lines from a File

# Open the file in read mode
with open('example.txt', 'r') as file:
    # Read all lines from the file
    lines = file.readlines()

# Print the list of lines
print(lines)

In this example, the file example.txt is opened, and the readlines() method is used to read all lines from the file. The result is a list where each element is a line from the file.

2.2 Processing Lines Individually

# Open the file in read mode
with open('example.txt', 'r') as file:
    # Read all lines from the file
    lines = file.readlines()

# Process each line
for line in lines:
    print(line.strip())  # Print each line without the newline character

This example reads all lines from the file and processes each line by stripping the newline character and printing it.

3. Handling Large Files

When working with very large files, reading all lines at once using readlines() might consume a lot of memory. In such cases, consider processing the file line by line using a loop:

# Open the file in read mode
with open('large_file.txt', 'r') as file:
    # Process each line individually
    for line in file:
        print(line.strip())  # Print each line without the newline character

This approach reads and processes each line one at a time, which is more memory-efficient for large files.

4. Summary

The readlines() method in Python is a convenient way to read all lines from a file into a list. Each line is returned as a string, including the newline character. For large files, consider processing lines one at a time to manage memory usage efficiently. Understanding how to use readlines() effectively allows you to handle and manipulate file data with ease.