log file parsing python

2019-02-17 20:53发布

I have a log file with arbitrary number of lines. All I need is to extract is one line of data from the log file which starts with a string “Total”. I do not want any other lines from the file.

How do I write a simple python program for this?

This is how my input file looks

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

I am trying to get an output file which looks like

TestName     id      TPS         GRE
Totals       64      129.61      145.64

Ok.. So I wanted only the 1st, 2nd, 4th and 5th column from the input file but not others. I am trying the list[index] to achieve this but getting a IndexError: (list index out of range ). Also the space between 2 columns are not the same so i am not sure how to split the columns and select the ones that i want. Can somebody please help me with this. below is the program I used

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]

2条回答
不美不萌又怎样
2楼-- · 2019-02-17 21:30
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
查看更多
男人必须洒脱
3楼-- · 2019-02-17 21:39
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])
查看更多
登录 后发表回答