简体   繁体   English

Python将'N'字节数据写入二进制文件

[英]Python Writing 'N' bytes data to Binary file

I have following data in Excel sheet, 1st column is number of bytes, 2nd column is its data (dat is in decimal,hex,ip address format) 我在Excel工作表中有以下数据,第一列是字节数,第二列是其数据(日期为十进制,十六进制,ip地址格式)

Question is how to write these into binary file, like in 1 bytes data,write 0x01,then 2 bytes data, write 0xAABB,then in 4 bytes data,write 10080000(dec)..etc even ip address in 4 bytes,write 10.65.84.8 问题是如何将这些写入二进制文件,如先写入1字节数据,然后写入0x01,然后写入2字节数据,写入0xAABB,然后写入4字节数据,再写入10080000(dec).. etc甚至将IP地址写入4字节,写入10.65 .84.8

Questions: 1)is it required to convert all data to one format (ie decimal or hex) ? 问题: 1)是否需要将所有数据转换为一种格式(即十进制或十六进制)? 2) are there inbuilt functions which gives write(num_of_bytes, value) ? 2)是否有内置函数可以提供write(num_of_bytes,value)?

File.xls File.xls

Number of bytes Data 字节数数据

1             0x01 (hex)
2             0xAABB
4             10080000
2             100
4             18181818 (decimal)
4             10.65.84.8(ip address)

i am new to python and have done following to read data from Excel(cvs) sheet 我是python的新手,并已完成以下操作以从Excel(cvs)工作表中读取数据

def open_file():
    book = xlrd.open_workbook('file.csv') 
    # get the first worksheet
    first_sheet = book.sheet_by_index(0)

    # read a cell
    cell = first_sheet.cell(0,0)
    num_rows = first_sheet.nrows 
    num_cols = first_sheet.ncols 

    for m in range(0, num_rows):
        for n in range(0, num_cols):
            cell = first_sheet.cell(m,n)
            print 'cell value %d',cell.value

You can use struct , pack and unpack to read and write binary data, the best solution I found and the cleanest is to handle data in hex() format. 您可以使用struct ,pack和unpack读取和写入二进制数据,这是我发现的最佳解决方案,而最干净的方法是处理hex()格式的数据。 Also pay attention to the indianness of your machine, when you will write and read, is it on the same machine! 另外,还要注意您的机器的印度性,即您将要在同一台机器上进行读写时!

Cheers, 干杯,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM