Python将“N”个字节数据写入二进制文件

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

问题是如何将这些写入二进制文件,如在1字节的数据中,写入0x01,然后写入2个字节的数据,写入0xAABB,然后在4个字节的数据中,写入10080000(dec)等等甚至4个字节的ip地址,写入10.65 .84.8

问题: 1)是否需要将所有数据转换为一种格式(即十进制或hex)? 2)是否有内置的函数可以写(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)工作表中读取数据

 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 

您可以使用结构 ,打包和解包来读取和写入二进制数据,我发现的最好的解决scheme,最干净的是以hex()格式处理数据。 还要注意你的机器的印度,当你会写和读,是在同一台机器!

干杯,