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

Python Writing 'N' bytes data to Binary file

我在 Excel sheet 中有以下数据, 第一列是字节数,第二列是它的数据(dat 是十进制,十六进制,ip 地址格式)

问题是如何将这些写入二进制文件,比如 在1字节数据中,写入0x01,然后2字节数据,写入0xAABB,然后 在 4 字节数据中,写入 10080000(dec)..etc 在 4 字节中写入偶数 ip 地址,写入 10.65.84.8

问题: 1)是否需要将所有数据转换为一种格式(即十进制或十六进制)? 2) 是否有提供 write(num_of_bytes, value) ?

的内置函数

File.xls

数据字节数

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

我是 python 的新手,已经完成以下操作以从 Excel(cvs) sheet

中读取数据
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

你可以使用struct,打包和解包来读写二进制数据,我找到的最好的解决方案也是最干净的是处理hex()格式的数据。还要注意你机器的印度性,你写和读的时候,是在同一台机器上吗!

干杯,