python - match a pattern and select specific lines in a file -
i have text file displayed below. select 2 lines (line 1 , line 2) under class 10 block only.
thu may 29 14:16:00 pdt 2014 class 09 line 0 line 1 line 2 -- class 10 line 0 line 1 line 2 -- class 11 line 0 line 1 line 2 -- thu may 29 14:20:00 pdt 2014 class 09 line 0 line 1 line 2 -- class 10 line 0 line 1 line 2 -- class 11 line 0 line 1 line 2 --
i have tried following, linecache
grabs line 1 only. find way grab line1 first line2. idea? thanks
numoflines = sum(1 line in open('text.txt')) print(num_lines) in range(start,numoflines,step): linea = linecache.getline('text.txt', i) print linea
numoflines = sum(1 line in open('text.txt'))
this line counts lines in file , that's it. not want.
not sure why you'd want linecache
. , don't show how compute start
or step
, bug is.
what want this:
def reading_function(): searching = true linestoread = 2 open('text.txt') f: line in f: if searching , line.strip() == "class 10": searching = false elif not searching: print line.strip() linestoread -= 1 if linestoread == 0: return
Comments
Post a Comment