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
- 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:
- Open the file in read mode
To open a file, pass the file path and the access mode
rto theopen()function, for example,with open(r'File_Path', 'r') as fp:to read a file. - 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. - Create a list to store the lines
Create an empty list to store the content of the lines you read.
- 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. - 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
breakafter 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.

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
linenofrom the file namedfilename. 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
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.
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.
startis the index of the first line you want. Indexes start at 0, so line 1 has index 0.endis the index where the slice stops. The line atenditself 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
Output:
['Third line\n', 'Fourth line\n', 'Fifth line\n']
Example: Read line 8
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()
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.
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:
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.
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.
Output:
['Seventh line', 'Eighth line']
Conclusion
| Method | Best for | Loads whole file? |
|---|---|---|
enumerate(fp, start=1) in a for loop | Specific line numbers in any file size | No |
itertools.islice(fp, start, stop) | A range of lines in a large file | No |
linecache.getline(path, n) | Reading many lines repeatedly from the same file | Yes (cached) |
fp.readlines()[start:end] | Small files, simplest code | Yes |
collections.deque(fp, maxlen=n) | The last N lines | No (keeps only N lines) |
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.
