[英]Return last occurence of search term in python3
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"我想阅读文件并只获取搜索词的最后一行:“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?我怎样才能得到最后一次出现?
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.在 for 循环结束后返回它,以便返回最后匹配的值。
with open("temp_log.out","r") as f:
for line in f.readlines():
if "Get_balance" in line:
result = line
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.