Wednesday, September 2, 2009

Print last instance of file - python example


Input file:

$ cat data.txt
k:begin:0
i:0:66
i:1:76
k:end:0
k:begin:7
i:0:55
i:1:65
i:2:57
k:end:7
k:begin:2
i:0:10
i:1:0
k:end:7
k:begin:2
i:0:46
k:end:7
k:begin:9
i:0:66
i:1:56
i:2:46
i:3:26
k:end:7

Required: Print last instance of the above file. One instance being from "k:begin" to "k:end"

The python program:

result =[]
all = open("data.txt").readlines()
for line in all[::-1]: #start from last ;proceed up
f=line.split(":")
if f[0]=="k" and f[1]=="end":
continue
elif f[0]=="k" and f[1]=="begin":
break
else: result.append(line)
print result
print "\nlast instance is\n"
print ''.join(result[::-1]) #reverse


Executing it:

$ python ins.py
['i:3:26\n', 'i:2:46\n', 'i:1:56\n', 'i:0:66\n']

last instance is

i:0:66
i:1:56
i:2:46
i:3:26



Related post:
- Print first few instances from file using python

0 Comments: