【发布时间】:2017-06-16 11:57:31
【问题描述】:
我是 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
...................
....................***
【问题讨论】:
-
第一次找到您的文本时,您
break退出了循环。尝试删除break
标签: python file directory readfile writefile