Leandro Penedo
Leandro Penedo

Reputation: 9

move backwards when iterate a for in a file

imagine this situation:

a file with 1000 lines. the name of the file is file.txt

file = file.txt
word = 'error'
for line in file:
    if word in line:
        execute things

if I want the 8 lines BEFORE the line with the word "error", how I get it?

Upvotes: 0

Views: 124

Answers (2)

Olvin Roght
Olvin Roght

Reputation: 7812

You can use combination of collections.deque() with fixed length and itertools.takewhile().

from collections import deque
from itertools import takewhile

with open("file.txt") as f:
    lines = deque(takewhile(lambda l: "error" not in l, f), maxlen=8)
print(*lines, sep="", end="")

Upvotes: 0

azro
azro

Reputation: 54148

Read the file and save the lines in a deque of a fixed size

from collections import deque

file = "file.txt"
word = 'error'

lines = deque(maxlen=8)
with open(file) as f:
    for line in f:
        if word in line:
            break
        lines.append(line)

print(lines)

Upvotes: 1

Related Questions