Peter
Peter

Reputation: 535

Write a raw binary file with NumPy array data

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.

Upvotes: 43

Views: 114142

Answers (3)

Alexey Antonenko
Alexey Antonenko

Reputation: 2627

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)

Upvotes: 0

Jay M
Jay M

Reputation: 4287

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()

Upvotes: 8

Bi Rico
Bi Rico

Reputation: 25813

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

array.astype('int16').tofile(filename)

Upvotes: 84

Related Questions