How to read a specific line from a text file in Python

To read a specific line from a text file in Python you can use readlines() or you can also import linecache. Here we gonna learn reading a specific line from a text file in Python for both large and small files.

We can achieve the line reading in Python with several methods but we will show you the easiest method first. Then we will see other methods.

In my previous Python tutorials, I have shown you several things you can do with a text file like

Read a specific line from a text file in Python

Code snippet:

file_variable = open('filename.txt')
all_lines_variable = file_variable.readlines()
print(all_lines_variable[specific_line_number - 1])

This is the easiest way to read a particular line from a text file in Python.



  • Where file_variable is the variable name.
  • all_lines_variable – This is the variable to hold the lines as an Object
  • all_lines[specific_line_number – 1] – If you want to read the line no 15 then put 14 in the square brackets.

A simple example of reading a particular line from a text file

Assume that we have a text file with the file name this_is_file.txt

Here is the content of the text file:

I am line no 1
I am line no 2
I am line no 3
I am line no 4
I am line no 5
I am line no 6
I am line no 7
I am line no 8
I am line no 9
I am line no 10

Now we have to read the texts from line no 5.

Then we will use the below code:

file = open('this_is_file.txt')
all_lines = file.readlines()
print(all_lines[4])

Output:

I am line no 5

Read a specific line from a text file in Python using linecache module

I love Python just because of its cool built-in modules.

Thankfully Python has linecache module which allows us to get any particular line from any file.

See an example,

Now, suppose you are told to read the line no 7 from the text file.

Here is the code:

import linecache
print(linecache.getline('this_is_file.txt',7))

Output:

I am line no 7

To know more about the linecache module see the linecache documentation

Leave a Reply

Your email address will not be published. Required fields are marked *