Fred
Fred

Reputation: 21

How to grep in python the last line?

I have this code:

with open('gauss.log', 'r') as f:
    lines = f.read().splitlines()
for line in lines:
     if line.__contains__('SCF Done'):
       print(line.split()[4])

now my problem is that I got something like, output:

-966.460358542
-966.462639325
-966.462959240
-966.463091939
-966.463234242
-966.463376736
-966.463488664
-966.463497061
-966.463527583
-966.463547506
-966.463549649
-966.463566858
-966.463575344
-966.463585840
-966.463589645
-966.463596480
-966.463602018
-966.463606042
-966.463607554
-966.463608071
-966.463608088

but I need only the last number of the last SCF Done cycle, how I can correct my script? I want just to grep the last SCF Done, like the "tail -1" option.

Upvotes: 1

Views: 310

Answers (3)

Evan L
Evan L

Reputation: 101

The most efficient answer posted is by MrGeek.

Below is a less efficient method, but is a useful look at filters - in case you wish to further process your full data set, and keep a list of all of your SCF Done values:

Read in your lines like you did before:

with open('gauss.log', 'r') as f: lines = f.read().splitlines()

Then filter them for all lines containing only SCF Done:

filteredLines = list(filter(lambda line: 'SCF Done' in line, lines))

Then take the last element of your filteredLines:

print(filteredLines[-1])

Upvotes: 0

Djaouad
Djaouad

Reputation: 22776

If I understand you correctly, you want to loop backwards over the lines and get the first match then stop searching (saves time, saves space):

for line in reversed(lines):    #   reversed : the name explains it all
    if 'SCF Done' in line:      #   found one while searching backwards
        print(line.split()[4])  #   print the number
        break                   #   stop searching

Upvotes: 1

Prune
Prune

Reputation: 77857

Save only the most recent one. When you run out of lines, print that one alone. Your print has to be outside of the loop.

for line in lines:
    if 'SCF Done' in line:
        last = line.split()[4]

print(last)

Upvotes: 0

Related Questions