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