How to read four lines at a time from file in python

Viewed 43

I want to read 4 or 6 lines at a time. I hope you guys can help me with this problem.

with open('readme.txt') as f:
    list_of_4tuples = [ (line,f.readline()) for line in f ]
for (line1,line2,line3,line4) in list_of_4tuples: # Work with them in pairs.
    print(f'a: {line1}{line2}{line3}{line4}')
2 Answers

(1, 2, 3, 4) then (2, 3, 4, 5)

with open('readme.txt') as f:
    lines = f.read().splitlines()

for (line1, line2, line3, line4) in zip(lines, lines[1:], lines[2:], lines[3:]): # Work with them in pairs.
   
    print(f'a: {line1}{line2}{line3}{line4}')

In case you don't lines are to be repeated.

(1, 2, 3, 4) then (5, 6, 7, 8)

with open('readme.txt') as f:

    for (line1, line2, line3, line4) in zip(f, f, f, f):
    
        print(f'a: {line1}{line2}{line3}{line4}')

You can create four iterators that run through the lines at the same time at separate offsets.

with open('readme.txt') as f:
    lines = f.readlines()

iterators = [iter(lines) for _ in range(4)]
for k in range(1, 4):
    for j in range(4-k, 4):
        next(iterators[j]) # advance the iterators

for line1, line2, line3, line4 in zip(*iterators):
    ...
Related