我需要用Python編寫一個很長的整數和浮點數列表,這與fwrite
在C語言中以二進制形式相同。如何用Python將變量寫入二進制數據?
這是創建我正在使用的另一段代碼的輸入文件所必需的。
這樣做的最好方法是什麼?
我需要用Python編寫一個很長的整數和浮點數列表,這與fwrite
在C語言中以二進制形式相同。如何用Python將變量寫入二進制數據?
這是創建我正在使用的另一段代碼的輸入文件所必需的。
這樣做的最好方法是什麼?
看一看numpy的:numpy tofile:
隨着陣列的方法 'TOFILE' 你可以寫二進制數據:
# define output-format
numdtype = num.dtype('2f')
# write data
myarray.tofile('filename', numdtype)
另一種方法是使用memmaps:numpy memmaps
# create memmap
data = num.memmap('filename', mode='w+', dtype=num.float, offset=myoffset, shape=(my_shape), order='C')
# put some data into in:
data[1:10] = num.random.rand(9)
# flush to disk:
data.flush()
del data
你可以用struct模塊簡單地做到這一點。
例如,寫的32位整數的列表中的二進制:
import struct
ints = [10,50,100,2500,256]
with open('output', 'w') as fh:
data = struct.pack('i' * len(ints), *ints)
fh.write(data)
會寫'\n\x00\x00\x002\x00\x00\x00d\x00\x00\x00\xc4\t\x00\x00\x00\x01\x00\x00'
使用'struct'模塊。 – martineau