首页 > 编程语言 > 详细

python分析二进制文件写入excel

时间:2019-10-25 12:27:25      阅读:268      评论:0      收藏:0      [点我收藏+]
import os
import sys
import struct
import binascii
import xlwt

def ParseData(parsebytes):
    i=0
    j=1
    data_len=len(parsebytes)
    while(i<data_len-1):
        try:
            send_flag=struct.unpack('b',parsebytes[i+2:i+3])[0]
            pint_id=struct.unpack('<H',parsebytes[i+3:i+5])[0]  
            dev_id=struct.unpack('<H',parsebytes[i+5:i+7])[0]  
            order=struct.unpack('<I',parsebytes[i+7:i+11])[0]  
            cur_time=struct.unpack('<I',parsebytes[i+11:i+15])[0]
            cur_data=struct.unpack('<I',parsebytes[i+39:i+43])[0]
            #写入excel表格进行后续分析
            sheet.write(j, 0, send_flag)
            sheet.write(j, 1, pint_id)
            sheet.write(j, 2, dev_id)
            sheet.write(j, 3, order)
            sheet.write(j, 4, cur_time)
            sheet.write(j, 5, cur_data)
        except:
            print('memory is overflow')        
        finally:
            i=i+47
            j=j+1


 
#切换到指定目录
os.chdir(r'C:\Users\Usmart\Desktop\file_test')

#创建excel表格
book=xlwt.Workbook(encoding="utf-8",style_compression=0)
sheet = book.add_sheet('表1', cell_overwrite_ok=True) #cell_overwrite_ok,表示是否可以覆盖单元格
sheet.write(0, 0, '发送标志')
sheet.write(0, 1, '采集点ID')
sheet.write(0, 2, '设备ID')
sheet.write(0, 3, '流水号')
sheet.write(0, 4, '采集时间')
sheet.write(0, 5, '设备数据')

#读取历史数据的二进制文件进行解析
fp=open("history.dat",'rb') 
filedata = fp.read()
ParseData(filedata)
print('Auto test finish')
fp.close()

#保存并生成excel文件
book.save('历史统计.xls') 

python分析二进制文件写入excel

原文:https://www.cnblogs.com/retry/p/11737141.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!