You can
- read all, store all in a list, reverse all and take first 10 lines that contain
,Kes
- your approach - takes lots of storage and time
- use Kasramvd's approach wich is francly far more elegant then this one - leveraging iterable and islice
- read each line yourself and check if
,Kes
in it, if so queue it:
from collections import deque
# create demodata
with open ("filename","w") as f:
for n in range (20):
for p in range(20):
f.write("some line {}-{}\n".format(n,p))
f.write("some line with {} ,Kes \n".format(n))
# read demodata
q = deque(maxlen=10)
with open("filename") as f:
for line in f: # read one line at time, not huge file at once
if ',Kes' in line: # only store line if Kes in it
q.append(line) # append line, size limit will make sure we store 10 at most
# print "remebered" data
print(list(q))
Output:
['some line with 10 ,Kes \n', 'some line with 11 ,Kes \n', 'some line with 12 ,Kes \n',
'some line with 13 ,Kes \n', 'some line with 14 ,Kes \n', 'some line with 15 ,Kes \n',
'some line with 16 ,Kes \n', 'some line with 17 ,Kes \n', 'some line with 18 ,Kes \n',
'some line with 19 ,Kes \n']
You will not have the whole file in RAM at once as well, at most 11 lines (curr line + deque holding 10 lines and it only remembers lines with ,Kes
in it.