How to Read a Specific Line from a Text File in Python?

Recently in a Python webinar, someone asked me how to read a specific line from a text file in Python. After researching and experimenting with various methods I found four effective methods to accomplish this task. In this tutorial, I will share my findings along with suitable examples and screenshots of executed example code.

Read a Specific Line from a Text File in Python

Let us learn how to read a specific line from a text file in Python.

Read How to Read the Last Line of a File in Python?

Method 1: Use readlines() Method

The readlines() method in Python reads all lines in a file and stores them in a list. You can then access specific lines using their index.

def read_specific_line(file_path, line_number):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        if 0 <= line_number < len(lines):
            return lines[line_number].strip()
        else:
            return "Line number out of range"

# Example usage
file_path = 'sample.txt'
line_number = 4
print(read_specific_line(file_path, line_number))

I executed the above example code and added the screenshot below.

Read a Specific Line from a Text File in Python

This method is simple but can be inefficient for very large files since it reads the entire file into memory.

Check out How to List Files in a Directory with Python?

Method 2: Use enumerate() Method

The enumerate() function in Python can be used to loop through the file line by line, which is more memory-efficient.

def read_specific_line(file_path, line_number):
    with open(file_path, 'r') as file:
        for current_line_number, line in enumerate(file):
            if current_line_number == line_number:
                return line.strip()
    return "Line number out of range"

# Example usage
file_path = 'sample.txt'
line_number = 4
print(read_specific_line(file_path, line_number))

I executed the above example code and added the screenshot below.

How to Read a Specific Line from a Text File in Python

Read How to Read the First Line of a File in Python?

Method 3: Use linecache Module

The linecache module in Python provides a simple way to read any line from a file without loading the entire file into memory.

import linecache

def read_specific_line(file_path, line_number):
    line = linecache.getline(file_path, line_number + 1)
    return line.strip() if line else "Line number out of range"

# Example usage
file_path = 'sample.txt'
line_number = 4
print(read_specific_line(file_path, line_number))

I executed the above example code and added the screenshot below.

Read a Specific Line from a Text File in Python linecache Module

Check out Python Get Filename From Path

Method 4: Use islice from itertools

The islice function from the itertools module in Python allows you to efficiently skip lines until you reach the desired one.

from itertools import islice

def read_specific_line(file_path, line_number):
    with open(file_path, 'r') as file:
        line = next(islice(file, line_number, line_number + 1), None)
        return line.strip() if line else "Line number out of range"

# Example usage
file_path = 'sample.txt'
line_number = 4
print(read_specific_line(file_path, line_number))

Example: Extract Data from a Log File

Let’s say you have a log file server.log and you need to extract the 10th line to check for a specific error message.

log_file_path = 'server.log'
line_number = 9  # Remember, line numbers start from 0

error_message = read_specific_line(log_file_path, line_number)
print(f"Error message on line {line_number + 1}: {error_message}")

Read Python File methods

Conclusion

In this article, I helped you learn how to read a specific line from a text file in Python. I explained mainly four methods to achieve this task such as using readlines() methods, using enumerate() method, using linecache module, and using islice from itertools. I also covered a real-time example.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.