Reading in a text file in a set line range

You can use itertools.islice() on the file object and use iteration to read only specific lines:

import itertools

with open(file_to_save, "r") as text_file:
    for line in itertools.islice(text_file, 19, 52):
         # do something with line

would read lines 20 through to 52; Python uses 0-based indexing, so line 1 is numbered 0.

Using the file object as an iterator gives you a lot of flexibility; you can read extra lines by calling next() on the file object, for example, advancing the line 'pointer' as you do so.

When using the file as an iterable, don't use readline(); the two techniques are not easily mixed.


You can do two things. You can use enumerate(), and use an if statement:

text_file = open(file_to_save, "r")
lines = []
for index, text in enumerate(text_file):
    if 19 <= index <= 51:
        lines.append(text)

Or instead, you can use readlines() and then slice:

text_file = open(file_to_save, "r")
lines = text_file.readlines()
lines = lines[19:52]

Tags:

Python

File