我有几个文件以“.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的新手,看到python的强大功能,我觉得有一种更强大、更高效的方法可以做到这一点。可能有一个简短的清单来做这种事情?请帮忙
佩斯作品:
这里我们取最后4行,除了文件的最后一行
从这些线,我们打破了结肠
现在我们试着从第二个得到一个数字,从第一个得到一个键,然后加到总数中
如果我们发现了一个不是数字的东西,或者一个不是我们要找的钥匙,我们就会打印一个错误
相关问题 更多 >
编程相关推荐