【问题标题】:Python, keyword searching code in a large .log filePython,大型 .log 文件中的关键字搜索代码
【发布时间】: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


【解决方案1】:

for 循环中的 break 行将完全结束循环,因此它只会调用一次 important.append(lines) - break 在这里没有用处。

另外我假设你的print('done') 行应该是左边的两个缩进级别,表示循环已经完成!

【讨论】:

  • 谢谢,revoving break 和缩进帮助!现在我得到了每个值:),但是它们都在同一条线上相互连接,有什么方法可以解决这个问题吗?以便在每一行而不是同一行上显示一个值
猜你喜欢
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 2012-07-11
  • 2019-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多