Reputation: 9
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
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
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