【问题标题】:log file parsing python日志文件解析python
【发布时间】:2013-06-05 17:16:35
【问题描述】:

我有一个包含任意行数的日志文件。我只需要从日志文件中提取一行数据,该数据以字符串“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: (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]

【问题讨论】:

  • Python 对于这个任务来说似乎有点过分了...... grep 不是更快吗?

标签: python parsing


【解决方案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

【讨论】:

    【解决方案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])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 2016-01-31
      相关资源
      最近更新 更多