Write a raw binary file with NumPy array data

Question:

I’d like to save the contents of a numpy float array into a raw binary file as signed 16 bit integers. I tried to accomplish this using ndarray.tofile but I can’t figure out the right format string. It seems that the file is saved in double format, mo matter how I choose the format string. How do I do this?
Thanks.

Asked By: Peter

||

Answers:

I think the easiest way to do this is to first convert the array to int16,

array.astype('int16').tofile(filename)
Answered By: Bi Rico

Take a look at the struct module, try this example:

import struct
import numpy

f=open("myfile","wb")
mydata=numpy.random.random(10)
print(mydata)
myfmt='f'*len(mydata)
#  You can use 'd' for double and < or > to force endinness
bin=struct.pack(myfmt,*mydata)
print(bin)
f.write(bin)
f.close()
Answered By: Jay M

You may use scipy.io.savemat which allows to save a dictionary of names and arrays into Matlab-style file:

import scipy.io as sio
sio.savemat(filename, pydict)

Here pydict may be = {‘name1’:np.array1, ‘name2’:np.array2,…}

To load the dict you just need:

pydict = sio.loadmat(filename)
Answered By: Alexey Antonenko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.