我是Python新手,我正在构建一个关键字搜索程序,该程序应该在大型.log文件中找到相同的每个单词(目前,单词“时间戳”)并将值存储在单独的.log文件中。日志文件。
这是我编写的代码,我的问题是我只得到第一次“时间戳”在.log文本新文件中弹出,而不是我想要的+100次其他时间...
帮忙? :)
<小时/>def 搜索(文件名,文本): 重要=[]
with open(filename) as f: #open search file
f = f.readlines() #read searrch file
for lines in f:
if text in lines: #if keyword is found take all lines
important.append(lines) #store all found keywords
print('done')
break
# file or 'sorted.txt'
with open('sorted.log', 'w') as file_handler:
file_handler.write(f"{filename}\n Status: {important} \n")
search(r'C:\Users\AppData\Local\Programs\Python\search\OJW74.log', 'Time stamp:') # search path
<小时/>
***前。 (.log文件像这样锁定)
Complete Response: 1636 59 02 FF
Time stamp: 9792463
Time between request and response(P2 time): 42 ms
Complete Response: 1636 59 02 FF
Time stamp: 9392463
Time between request and response(P2 time): 42 ms
Complete Response: 1636 59 02 FF
Time stamp: 9794463
Time between request and response(P2 time): 42 ms
...................
....................***
最佳答案
for 循环中的 break
行将完全结束循环,因此它只会调用 important.append(lines)
一次 - break
在这里没有任何作用。
此外,我假设您的 print('done')
行应该向左有两个缩进级别,以表示循环已完成!
关于Python,在大型 .log 文件中搜索关键字代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44588711/