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相對來說比較新,並且看到它的強大功能,我覺得可能有更強大有效的方法來做到這一點。可能有一個短名單理解做這種東西?請幫忙。
謝謝。我喜歡異常處理部分,它非常好。我不想閱讀整個文件,所以我仍然喜歡使用我的getLastXLines代碼。我會給你一個投票,並等待任何更好的答案:) – user3885927 2014-09-13 00:07:37
如果你不介意我問,你怎麼只讀最後幾行?最後我檢查過,文件不能這樣工作,除非你使用一些使用每個文件記錄的模糊操作系統。 – user2085282 2014-09-13 00:37:50
查看https://docs.python.org/2/tutorial/inputoutput.html具體來說,file.seek和file.tell可讓您以任意順序讀取特定字節 – user3885927 2014-09-13 01:04:40