2014-09-12 108 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