Write a numpy array with its size to binary

I need to write a 2D numpy array to a file, including its dimensions, so that I can read it from a C ++ program and create the corresponding array.

I wrote simple code that saves an array and can be read with C ++, but if I try to write the size of the array first, it always gives me an error.

Here is my simple python code:

1 file = open("V.bin","wb") 2 file.write(V.shape) 3 file.write(V) 4 file.close() 

The second line gives an error, I also tried:

 n1, n2 = V.shape file.write(n1) file.write(n2) 

But that doesn't work either.

I am adding an error message:

Traceback (last last call): file.write (V.shape [0]) TypeError: should be a string or buffer, not int

Thanks!

+4
source share
2 answers

You can use numpy.savetext if you want to save it as ascii.

Alternatively (since you seem to be dealing with binary data), if you want to preserve the raw data stream, you can use ndarray.tostring to get a string of bytes that you can send directly to the file.

The advantage of this approach is that you can create your own file format. The disadvantage is that you need to create a string in order to actually write it to a file.


And since you say that you are getting an error in the second line, this is an error because f.write expecting a line. You are trying to pass it tuple or int s. You can use struct.pack to solve this problem:

 f.write(struct.pack('2i',*array.shape)) 
+2
source

You can use numpy.save () , which is saved in binary format.

+5
source

Source: https://habr.com/ru/post/1444817/


All Articles