[Numpy-discussion] difficulties with numpy.tofile()

Robert Kern robert.kern at gmail.com
Mon Nov 17 00:47:05 EST 2008


On Sun, Nov 16, 2008 at 23:37, Catherine Moroney
<catherine.m.moroney at jpl.nasa.gov> wrote:
> Hello,
>
> I'm having problems writing a 2-dimensional numpy array out to a binary
> file using the "tofile" method.  The call to "tofile" appears to
> succeed,
> but when I check the length of the binary file I find that it's longer
> than what is expected, given the calculation of nrows*ncolumns*nbytes.
>
> The array that I'm writing out to the file is the result of running
> kmeans2 (from scipy), so I'm expecting that the datatype is numpy.int32.
> Is there an easy way to check what the datatype of a numpy array is?

some_array.dtype

> Yet, the file that results from the call:
>    data.tofile('./data1.bin','int32') is longer than it should be.
>
> Using "float32" as the datatype results in an even larger file, so it's
> still longer than expected.

That argument is not the datatype. If you provide that argument, it
specifies that you are outputting ASCII, not binary, and are using
that value as the separator. Just use the filename and nothing else.
If you need the data as a different type, coerce the array using the
.astype() method.

  http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tofile.html

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list