Python,在大型 .log 文件中搜索关键字代码

标签 python file directory readfile writefile

我是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/

相关文章:

c - 文件 I/O 困惑

algorithm - 除了逐字节检查外,还有哪些其他方法可以确定两个文件内容是否相同?

linux - 如何比较bash中两个目录的内容?

delphi - 通过 installaware 安装我的应用程序后,我必须打开 windows 字体文件夹

python - 如何使用 moto 模拟 AWS Lambda

python - Django 使用多个数据库

python - Django 和 Stripe : How to send error messages?

Python-PyQt : restarting a thread which is finished

java - 如何在用java创建pdf后立即下载它

eclipse - 类的文件夹