0

I have a log file, that can be very long

2021-02-26 12:49:06.982823 API Get_balance
2021-02-26 12:49:06.983400 FILE Updated_balance /home/balance/balance26022021.json
2021-02-26 12:49:36.426180 INIT Analyst starting up...
2021-02-26 12:49:36.426312 FILE Creating balance26022021.json
2021-02-26 12:50:42.860993 INIT Analyst starting up...
2021-02-26 12:51:36.927115 INIT Analyst starting up...
2021-02-26 12:56:54.270294 INIT Analyst starting up...
2021-02-26 12:56:55.565137 API Get_balance

I want to read the file and get ONLY the very last line of my search term : "Get_balance"

        mysearchterm = "Get_balance"
        with open (self.__todays_log) as f:
            datafile = f.readlines()
        for line in datafile:
            if mysearchterm in line:
                print (line)
                #value = line.split()[4]
                return value

Using the code above, I am getting the first occurence.

How can I get the last occurence?

scandalous
  • 912
  • 5
  • 14
  • 25
  • 1
    This https://stackoverflow.com/a/23646049/12479639 is a good answer if reading the entire file is a performance issue. – Axe319 Feb 26 '21 at 14:05

1 Answers1

1

Because you are returning as soon as you get a match. return it after the for loop ends, so that the last matched value will be returned.

with open("temp_log.out","r") as f:
for line in f.readlines():
    if "Get_balance" in line:
        result = line
print(result)
bukli
  • 172
  • 2
  • 9