Getting the previous line in Jython
I want to print the line immediately before the searched string. How can I do that?
Lets say my two lines are
AADRG
SDFJGKDFSDF
and I 开发者_开发技巧am searching for SDF
. I have found SDFJGKDFSDF
, but how can I obtain the previous line AADRG
? Does file.readline()-1
work?
lastLine = ""
for line in lines:
if line.find("SDF"):
print lastLine
lastLine = line
or
lines = open("file").readlines()
for line in lines:
if "SDF" in line:
# test for not being the first line of course.
print lines[lines.index(line) - 1]
精彩评论