python txt文件数据转excel

txt content: perf.txt

2018-11-12 16:48:58
time: 16:48:58 load average: 0.62, 0.54, 0.56 mosquitto CPU: 5.9 MEM 1.6 tmmr CPU: 0.0 MEM 1.1
time: 16:48:59 load average: 0.62, 0.54, 0.56 mosquitto CPU: 25.0 MEM 1.6 tmmr CPU: 6.2 MEM 1.1
time: 16:49:00 load average: 0.65, 0.54, 0.56 mosquitto CPU: 5.9 MEM 1.6 tmmr CPU: 5.9 MEM 1.1
time: 16:49:01 load average: 0.65, 0.54, 0.56 tmmr CPU: 12.5 MEM 1.1 mosquitto CPU: 6.2 MEM 1.6
time: 16:49:03 load average: 0.65, 0.54, 0.56 tmmr CPU: 5.9 MEM 1.1 mosquitto CPU: 0.0 MEM 1.6
time: 16:49:04 load average: 0.65, 0.54, 0.56 mosquitto CPU: 5.9 MEM 1.6 tmmr CPU: 5.9 MEM 1.1
time: 16:49:05 load average: 0.60, 0.54, 0.56 mosquitto CPU: 16.7 MEM 1.6 tmmr CPU: 5.6 MEM 1.1
time: 16:49:06 load average: 0.60, 0.54, 0.56 mosquitto CPU: 5.6 MEM 1.6 tmmr CPU: 5.6 MEM 1.1
time: 16:49:07 load average: 0.60, 0.54, 0.56 tmmr CPU: 6.2 MEM 1.1 mosquitto CPU: 0.0 MEM 1.6

code: 

#coding=utf-8
import xlwt

workbook = xlwt.Workbook()
sheet1=workbook.add_sheet('tmmr',cell_overwrite_ok=True)
#style = "font:colour_index blue;"
#blue_style = xlwt.easyxf(style)

row0=[u"TIME",u"MOS_CPU",u"MOS_MEM",u"TMMR_CPU",u"TIMMR_MEM",u"Load Average_1",u"Load Average_5",u"Load Average_15"]
for i in range(0,len(row0)):
    sheet1.write(0,i,row0[i])
    #sheet1.write(0,i,row0[i],blue_style)


f = open('perf.txt') 
next(f) 
index = 1
for line in f: 
    data = line.strip('\n').split(' ')
    print data
    if data[7] =="tmmr":
        #print "********************************"
        #print data
        data[7],data[12] = data[12],data[7]
        data[8],data[13] = data[13],data[8]
        data[9],data[14] = data[14],data[9]
        data[10],data[15] = data[15],data[10]
        data[11],data[16] = data[16],data[11]
       # print data
        #print "********************************"
    sheet1.write(index,0,data[1])
    sheet1.write(index,1,float(data[9]))
    sheet1.write(index,2,float(data[11]))
    sheet1.write(index,3,float(data[14]))
    sheet1.write(index,4,float(data[16]))
    sheet1.write(index,5,float(data[4].strip(',')))
    sheet1.write(index,6,float(data[5].strip(',')))
    sheet1.write(index,7,float(data[6].strip(',')))
    index = index + 1

        

        
workbook.save('perf.xls')

结果输出:

 

posted on 2018-11-12 16:55  清明-心若淡定  阅读(10622)  评论(0编辑  收藏  举报