簡體   English   中英

Python 讀取日志文件並獲取包含特定單詞的行

[英]Python read log files and get lines containing specific words

我有日志文件(以 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。

您需要知道如何循環目錄中的文件正則表達式以確保您的日志文件格式與您循環的文件匹配如何打開文件如何循環打開文件中的行,以及如何檢查其中一行是否包含您要查找的內容

這里有一些代碼可以幫助您入門。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM