开发者

Getting the previous line in Jython

开发者 https://www.devze.com 2022-12-24 17:26 出处:网络
I want to print the line immediately before the searched string. How can I do that? Lets say my two lines are

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

精彩评论

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