Python Language Read a file between a range of lines


So 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 will read through the lines 13 to 20 as in python indexing starts from 0. So line number 1 is indexed as 0

As can also read some extra lines by making use of the next() keyword here.

And when you are using the file object as an iterable, please don't use the readline() statement here as the two techniques of traversing a file are not to be mixed together