【问题标题】:Python read log files and get lines containing specific wordsPython 读取日志文件并获取包含特定单词的行
【发布时间】:2013-04-15 14:11:40
【问题描述】:

我有日志文件(以 YYMMDD 格式命名),我想创建一个仅从文件中获取重要信息的脚本(例如包含 "O:NVS:VOICE" 的行)。我以前从未使用过 Python,所以请帮忙!

【问题讨论】:

  • 我们需要了解您已经尝试过的内容以及您遇到问题的地方。您需要帮助打开文件吗?解析那里的数据?打印/写出您感兴趣的信息?
  • 其实我刚刚在 python 中开始了我的项目,所以我仍在考虑解决方案,我想从有经验的人那里得到一些想法。脚本旨在获得就像我所说的那样,从服务器每天生成的日志文件中计算出特定的单词,然后将它们放入 mysql 数据库中,所以我不知道如何获取这些行,因为它们很多并且每天创建。 .

标签: python


【解决方案1】:

这应该可以让你很好地开始:

infile = r"D:\Documents and Settings\xxxx\Desktop\test_log.txt"

important = []
keep_phrases = ["test",
              "important",
              "keep me"]

with open(infile) as f:
    f = f.readlines()

for line in f:
    for phrase in keep_phrases:
        if phrase in line:
            important.append(line)
            break

print(important)

它绝不是完美的,例如没有异常处理或模式匹配,但你可以很容易地添加这些。查看正则表达式,这可能比短语匹配更好。如果您的文件很大,请逐行读取以避免 MemoryError。

输入文件:

This line is super important!
don't need this one...
keep me!
bla bla
not bothered
ALWAYS include this test line

输出:

['This line is super important!\n', 'keep me!\n', 'ALWAYS include this test line']

注意:这是 Python 3.3。

【讨论】:

  • 您可以通过循环文件对象而不是调用 readlines 来避免大文件的问题。只需将您的for line in f 移动到您的with 中并摆脱f.readlines()
【解决方案2】:

您需要知道如何使用loop over files in a directoryregular expressions to make sure your log file format matches to file you are looping overhow to open a filehow to loop over the lines in the open filehow to check if one of those lines contains what you are looking for

这里有一些代码可以帮助您入门。

with open("log.log" 'r') as f:
    for line in f:
        if "O:NVS:VOICE" in line:
            print line

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-20
    • 2015-12-18
    • 2021-10-12
    • 2022-01-22
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    相关资源
    最近更新 更多