kdev
kdev

Reputation: 291

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?

Upvotes: 1

Views: 466

Answers (1)

corn3lius
corn3lius

Reputation: 4985

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]

Upvotes: 4

Related Questions