2014-09-12 103 views
0

我有几个以“.log”结尾的文件。最后三行包含感兴趣的数据。解析数组内容并添加值

实施例的文件的内容(最后四行第四行是空的):

总计:150

成功:120

错误:30

我读这些内容转换成一个数组并试图找到一个优雅的方式来: 1)提取每个类别的数字数据(总计,成功,错误)。错误了,如果数字数据是不存在在第二部分 2)添加它们加起来

我想出了排除简洁下面的代码(getLastXLines函数)返回汇总:

def getSummaryData(testLogFolder): 
    (path, dirs, files) = os.walk(testLogFolder).next() 
    #aggregate = [grandTotal, successTotal, errorTotal] 
    aggregate = [0, 0, 0] 
    for currentFile in files: 
      fullNameFile = path + "\\" + currentFile 
      if currentFile.endswith(".log"): 
       with open(fullNameFile,"r") as fH: 
        linesOfInterest=getLastXLines(fH, 4) 
       #If the file doesn't contain expected number of lines 
       if len(linesOfInterest) != 4: 
        print fullNameFile + " doesn't contain the expected summary data" 
       else: 
        for count, line in enumerate(linesOfInterest[0:-1]): 
         results = line.split(': ') 
         if len(results)==2: 
          aggregate[count] += int(results[1]) 
         else: 
          print "error with " + fullNameFile + " data. Not adding the total" 

    return aggregate 

被python相对来说比较新,并且看到它的强大功能,我觉得可能有更强大有效的方法来做到这一点。可能有一个短名单理解做这种东西?请帮忙。

回答

1
def getSummaryData(testLogFolder): 
    summary = {'Total':0, 'Success':0, 'Error':0} 
    (path, dirs, files) = os.walk(testLogFolder).next() 
    for currentFile in files: 
      fullNameFile = path + "\\" + currentFile 
      if currentFile.endswith(".log"): 
       with open(fullNameFile,"r") as fH: 
        for pair in [line.split(':') for line in fH.read().split('\n')[-5:-2]]: 
         try: 
          summary[pair[0].strip()] += int(pair[1].strip()) 
         except ValueError: 
          print pair[1] + ' is not a number' 
         except KeyError: 
          print pair[0] + ' is not "Total", "Success", or "Error"' 
    return summary 

件由peice的:

fH.read().split('\n')[-5:-2] 

在这里,我们采取的最后4行除最后文件

line.split(':') for line in 

从这些线路中,我们打破由冒号

try: 
    summary[pair[0].strip()] += int(pair[1].strip()) 

现在我们尝试获取一个数字BER从第二,并从第一和一键添加到我们的总

except ValueError: 
    print pair[1] + ' is not a number' 
except KeyError: 
    print pair[0] + ' is not "Total", "Success", or "Error"' 

如果我们找到的东西,是不是一个数字,或者说是不是我们正在寻找一个关键,我们打印一个错误

+1

谢谢。我喜欢异常处理部分,它非常好。我不想阅读整个文件,所以我仍然喜欢使用我的getLastXLines代码。我会给你一个投票,并等待任何更好的答案:) – user3885927 2014-09-13 00:07:37

+0

如果你不介意我问,你怎么只读最后几行?最后我检查过,文件不能这样工作,除非你使用一些使用每个文件记录的模糊操作系统。 – user2085282 2014-09-13 00:37:50

+0

查看https://docs.python.org/2/tutorial/inputoutput.html具体来说,file.seek和file.tell可让您以任意顺序读取特定字节 – user3885927 2014-09-13 01:04:40