Read a file between a range of lines
suggest changeSo let’s suppose you want to iterate only between some specific lines of a file.
You can make use of itertools for that:
import itertools
with open('myfile.txt', 'r') as f:
for line in itertools.islice(f, 12, 30):
# do something here
This reads lines 13 through 30. islice stops before the end index, and Python indexes from 0, so line 1 is index 0.
You can also advance one line at a time with the next() built-in. When you are using the file object as an iterable, don’t also call readline() in that loop. The two ways of traversing a file should not be mixed.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents