Python读取日志文件并获取包含特定单词的行

时间:2013-04-15 14:11:40

标签: python

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

2 个答案:

答案 0 :(得分:14)

这应该让你开始很好:

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。

答案 1 :(得分:11)

您需要知道如何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