How to read a specific line from a text file in Python
This tutorial is going to show you how to read a specific line from a text file in Python using two different ways.
In the first example, we will see how to perform this task using the Python
readlines() function. In our second example, we will use the
linecache Python module for reading a specific line.
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
readlines() is the easiest way to read a specific line from a text file in Python. Below is given the code snippet:
file_variable = open('filename.txt') all_lines_variable = file_variable.readlines() print(all_lines_variable[specific_line_number - 1])
file_variableis 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.
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)
I am line no 5
Using the linecache Python 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.
Let’s see an example…
Suppose you are told to read line no 7 from the text file.
Here is the code:
import linecache print(linecache.getline('this_is_file.txt',7))
I am line no 7
To know more about the linecache module see the linecache documentation