Return 搜索词最后一次出现在 python3
Return last occurence of search term in python3
我有一个日志文件,可能会很长
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
我想读取文件并只获取搜索词的最后一行:“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
使用上面的代码,我得到了第一次出现。
我怎样才能得到最后一次出现?
因为你一找到匹配项就returning。 return 它在 for 循环结束后,这样最后匹配的值将被 returned.
with open("temp_log.out","r") as f:
for line in f.readlines():
if "Get_balance" in line:
result = line
print(result)
我有一个日志文件,可能会很长
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
我想读取文件并只获取搜索词的最后一行:“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
使用上面的代码,我得到了第一次出现。
我怎样才能得到最后一次出现?
因为你一找到匹配项就returning。 return 它在 for 循环结束后,这样最后匹配的值将被 returned.
with open("temp_log.out","r") as f:
for line in f.readlines():
if "Get_balance" in line:
result = line
print(result)