PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » File Handling » Read Specific Lines From a File in Python

Read Specific Lines From a File in Python

Updated on: December 4, 2026 | 4 Comments

This article shows how to read specific lines from a file by line number in Python, for example, only lines 4 and 7, a range of lines, or the last few lines.

Table of contents

  • Steps to Read Specific Lines From a File
    • Example: Read Specific Lines From a File by Line Number
  • linecache Module to Read a Line by Line Number
  • Use readlines() to Read a Range of Lines From a File
  • Generator to Read Lines From a File by Line Number
  • for Loop Over the File Object to Read Specific Lines
  • Read a Range of Lines From a Large File With islice()
  • Read the Last N Lines of a File
  • Conclusion

Steps to Read Specific Lines From a File

Let’s assume the file is very large (several GB), and you don’t want to read the whole file into memory, but only lines 5 and 120. To read specific lines from a text file, follow these steps:

  1. Open the file in read mode

    To open a file, pass the file path and the access mode r to the open() function, for example, with open(r'File_Path', 'r') as fp: to read a file.

  2. Create a list of line numbers

    Create a list with the numbers of the lines you want to read, for example, line_numbers = [4, 7] to read lines 4 and 7.

  3. Create a list to store the lines

    Create an empty list to store the content of the lines you read.

  4. Use a for loop with enumerate() to get each line and its number

    The enumerate() function adds a counter to an iterable. Pass the file object to enumerate(fp, start=1) and use it in a for loop to get each line with its line number, starting at 1.
    Note: Iterating over the file object doesn’t load the entire file into memory, so this is an efficient solution.

  5. Check the line number

    In each iteration, use an if condition to check the line number. If it is one you want, save the line in the list. Stop the loop with break after the last line you need.

Example: Read Specific Lines From a File by Line Number

The following code shows how to read a text file by line number in Python. The image below shows the content of the file used in the example.

In this example, we are reading lines 4 and 7 and storing them in a list. We pass start=1 to enumerate() so that the line numbers start at 1, like in a text editor.

text file
text file
with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
    # lines to read (counting from 1)
    line_numbers = [4, 7]
    # To store lines
    lines = []
    for i, line in enumerate(fp, start=1):
        # read line 4 and 7
        if i in line_numbers:
            lines.append(line.strip())
        elif i > 7:
            # don't read after line 7 to save time
            break
print(lines)Code language: Python (python)

Output:

['Fourth line', 'Seventh line']

linecache Module to Read a Line by Line Number

In this section, we’ll see how to read a line from a file by its line number using the linecache module.

Python’s linecache module is a convenient way to jump to a particular line in a text file, especially when you need to read several lines from the same file.

The linecache module allows one to get any line from a Python source file, while attempting to optimize internally, using a cache, the common case where many lines are read from a single file. This is used by the traceback module to retrieve source lines for inclusion in the formatted traceback.

Python Documentation

Use the linecache.getline() method to read specific line from a file.

linecache.getline(filename, lineno, module_globals=None)Code language: Python (python)
  • It returns line number lineno from the file named filename. Line numbers start at 1.
  • It doesn’t raise an error if the line or the file doesn’t exist. Instead, it returns an empty string.
  • The returned line includes the trailing newline character.

Example

import linecache

# read fifth line (line numbers start at 1)
line = linecache.getline(r"E:\demos\files\read_demo.txt", 5)
# strip() removes the trailing newline
print(line.strip())Code language: Python (python)

Output:

Fifth line

Note: linecache reads the whole file into memory the first time you access it and keeps it cached. So, it is fast when you read many lines from the same file, but it is not a good choice for very large files.

To read more than one line from a file with linecache, call getline() for each line number.

import linecache

line_numbers = [2, 4]
lines = []
for i in line_numbers:
    x = linecache.getline(r"E:\demos\files\read_demo.txt", i).strip()
    lines.append(x)
print(lines)Code language: Python (python)

Output:

['Second line', 'Fourth line']

If the file changes while your program is running, call linecache.checkcache(filename) or linecache.clearcache(). Otherwise, getline() may return the old, cached content.

Use readlines() to Read a Range of Lines From a File

If your file size is small and you are not concerned with performance, then the readlines() method is best suited.

Reading a whole file is fast when the file is only a few MB in size.

The readlines() method reads all lines from a file and returns them as a list. You can then use an index or a slice to pick the lines you need.

This is the most straightforward way to read specific lines from a file. It reads the entire file and then picks the lines you need.

Use readlines()[start:end] to read a range of lines.

  • start is the index of the first line you want. Indexes start at 0, so line 1 has index 0.
  • end is the index where the slice stops. The line at end itself is not included.
  • To read lines 3 to 5, use readlines()[2:5].
  • To read a single line, use an index, for example, fp.readlines()[2] reads the third line.

Example: Read line from 3 to 5

with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
    # read line number 3 to 5
    # index starts from 0
    x = fp.readlines()[2:5]
    print(x)Code language: Python (python)

Output:

['Third line\n', 'Fourth line\n', 'Fifth line\n']

Example: Read line 8

with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
    # read line 8 (index 7)
    x = fp.readlines()[7]
    print(x.strip())
# Output Eighth lineCode language: Python (python)

An index that doesn’t exist, for example, readlines()[20] for an 8-line file, raises an IndexError. Slicing never raises an error. It just returns fewer lines.

You can also use the readline() method to read the file one line at a time and stop when you’ve reached the lines you want. With this technique, you don’t need to read the entire file.

Example: Read lines 3 and 6 with readline()

# line numbers to read (counting from 1)
lines = [3, 6]
result = []
line_no = 0

with open("read_demo.txt", "r") as fp:
    while True:
        line = fp.readline()
        # an empty string means we reached the end of the file
        if not line:
            break
        line_no += 1
        if line_no in lines:
            result.append(line.strip())
        # stop once we have read the last line we need
        if line_no >= max(lines):
            break
print(result)Code language: Python (python)

Output:

['Third line', 'Sixth line']

Generator to Read Lines From a File by Line Number

A generator expression is a fast and compact way to read lines by line number.

If you need to read many lines from a large file, a generator is a good choice, because it doesn’t build a list of all the lines.

The function below accepts a file object and the line numbers to read, and returns a generator. Lines are produced one at a time as you iterate over the generator. We pass the line numbers as a set because checking membership in a set is faster than in a list.

# read by line numbers (counting from 1)
def get_lines(fp, line_numbers):
    return (x for i, x in enumerate(fp, start=1) if i in line_numbers)

with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
    # read line 4 and 7
    lines = get_lines(fp, {4, 7})
    # print each line
    for line in lines:
        print(line.strip())Code language: Python (python)

Output:

Fourth line
Seventh line

for Loop Over the File Object to Read Specific Lines

A file object is iterable, so you can loop over it directly and keep a line counter.

  • Use for loop to iterate each line from a file object
  • Use the if condition in each iteration of a loop to check the line number. If it matches, then save that line into a list.

Note: Iterating over a file object reads one line at a time, so this approach does not load the entire file into memory. Unlike the first example, though, it keeps reading until the end of the file. Add a break once you have all the lines you need.

Example:

# line numbers to read (counting from 1)
lines = [3, 6]
result = []

with open("read_demo.txt", "r") as fp:
    # access each line with its number
    for i, line in enumerate(fp, start=1):
        # check line number
        if i in lines:
            result.append(line.strip())
print(result)Code language: Python (python)

Output:

['Third line', 'Sixth line']

Read a Range of Lines From a Large File With islice()

itertools.islice() works like list slicing, but on any iterator, including a file object. It reads only up to the last line you need, so it is memory-efficient for large files.

from itertools import islice

with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
    # lines 3 to 5 (index 2 up to, but not including, 5)
    for line in islice(fp, 2, 5):
        print(line.strip())Code language: Python (python)

Output:

Third line
Fourth line
Fifth line

Read the Last N Lines of a File

To read the last lines, pass the file object to collections.deque with a maxlen. The deque keeps only the last maxlen lines while reading, so memory use stays small even for big files.

from collections import deque

with open(r"E:\demos\files\read_demo.txt", 'r') as fp:
    last_lines = deque(fp, maxlen=2)

print([line.strip() for line in last_lines])Code language: Python (python)

Output:

['Seventh line', 'Eighth line']

Conclusion

MethodBest forLoads whole file?
enumerate(fp, start=1) in a for loopSpecific line numbers in any file sizeNo
itertools.islice(fp, start, stop)A range of lines in a large fileNo
linecache.getline(path, n)Reading many lines repeatedly from the same fileYes (cached)
fp.readlines()[start:end]Small files, simplest codeYes
collections.deque(fp, maxlen=n)The last N linesNo (keeps only N lines)
Ways to read specific lines from a file

Remember that list indexes and enumerate() start at 0 by default, while people count lines from 1. Use enumerate(fp, start=1) or subtract 1 from the line number to avoid off-by-one mistakes.

Filed Under: Python, Python File Handling

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python File Handling

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python File Handling
TweetF  sharein  shareP  Pin

  Python File Handling

  • File Handling In Python
  • Create File in Python
  • Open a File in Python
  • Read File in Python
  • Write to File in Python
  • Python File Seek
  • Rename Files in Python
  • Delete Files in Python
  • Copy Files in Python
  • Move Files in Python
  • List Files in a Directory
  • File Handling Quiz

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com