Using Python 2.4, I am reading a large flat file and picking a particular line number. Now I want to search for a string, say, START
before that line number, and a string END
, after that line n开发者_如何学Cumber.
How do I get the line numbers of the nearest occurrences of the strings START
(before current line number) and END
(after current line number)?
How about this:
line_no = 1
# Seek the last START before reaching the target line.
start_line_no = -1
while line_no != target_line_no:
line = input.readline()
if line == "":
# File is shorter than you think.
break
line_no += 1
if START in line:
start_line_no = line_no
# Seek the first END after the target line.
end_line_no = -1
while true:
line = input.readline()
if line == "":
# END could not be found.
break
line_no += 1
if END in line:
end_line_no = line_no
break
print start_line_no, end_line_no
精彩评论