开发者

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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜