Skip to main content
 首页 » 编程设计

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

2025年05月04日14zhwl

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

请您参考如下方法:

这应该能让你很好地开始:

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。