Last Updated: February 25, 2016
·
13.25K
· mikkkee

Use Python to read file by N lines each time

from itertools import islice

def next_n_lines(file_opened, N):
    return [x.strip() for x in islice(file_opened, N)]

Each time next_n_lines(file_opened, N) is called, the function will return the next N lines from file_opened as a list.

Example:

with open("samplefile", 'r') as sample:
    lines_1_to_5 = next_n_lines(sample, 5)
    lines_6_to_10 = next_n_lines(sample, 5)