簡體   English   中英

日志文件解析python

[英]log file parsing python

我有一個任意行數的日志文件。 我只需要從日志文件中提取一行數據,該行以字符串“Total”開頭。 我不想要文件中的任何其他行。

我如何為此編寫一個簡單的python程序?

這是我的輸入文件的外觀

TestName     id         eno            TPS      GRE          FNP
Test 1205    1            0            78.00        0.00         0.02
Test 1206    1            0            45.00        0.00         0.02
Test 1207    1            0            73400        0.00         0.02
Test 1208    1            0            34.00        0.00         0.02

Totals       64           0            129.61       145.64       1.12

我試圖得到一個看起來像的輸出文件

TestName     id      TPS         GRE
Totals       64      129.61      145.64

好的..所以我只希望輸入文件中的第1,第2,第4和第5列而不是其他列。 我正在嘗試使用list [index]來實現這一點,但得到一個IndexError :(列表索引超出范圍)。 2列之間的空間也不一樣,所以我不知道如何拆分列並選擇我想要的列。 有人可以幫我這個。 以下是我使用的程序

newFile = open('sana.log','r')

for line in newFile.readlines():

    if ('TestName' in line) or ('Totals' in line):

        data = line.split('\t')

        print data[0]+data[1]
theFile = open('thefile.txt','r')
FILE = theFile.readlines()
theFile.close()
printList = []
for line in FILE:
    if ('TestName' in line) or ('Totals' in line):
         # here you may want to do some splitting/concatenation/formatting to your string
         printList.append(line)

for item in printList:
    print item    # or write it to another file... or whatever
for line in open('filename.txt', 'r'):
    if line.startswith('TestName') or line.startswith('Totals'):
        fields = line.rsplit(None, 5)
        print '\t'.join(fields[:2] + fields[3:4])

暫無
暫無

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

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