2013-05-16 40 views

回答

2

看一看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 
+0

這是一個簡單而有效的解決方案。非常感謝你! – bluewhale

+0

你不需要dtype作爲'tofile'的參數。其實這個文件是不正確的,如果我這樣做 – chaohuang

4

你可以用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'