日志文件解析python

2024-05-15 22:45:22 发布

您现在位置: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]来实现这一点,但得到了一个索引器错误:(list index out of range)。两列之间的间距也不一样,所以我不知道如何拆分列并选择所需的列。有人能帮我一下吗。下面是我使用的程序

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]

Tags: 文件字符串intest程序iddataindex
2条回答
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])
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

相关问题 更多 >