Home

ndarraytofile

ndarray.tofile, commonly referred to as ndarraytofile, is a method of NumPy's ndarray class that writes the elements of an array to a file. It accepts a file name or a file-like object as its first argument. The second argument, sep, controls the output format: if sep is an empty string (the default), the array is written as raw binary data; if sep is non-empty, the array is written as text with values separated by sep using the specified format string (the default format is a representation suitable for Python).

The data are written in the array’s memory order. For typical C-contiguous arrays, this corresponds to row-major

Reading data written with tofile is done with numpy.fromfile, which requires the correct dtype. If the file

Example:

import numpy as np

a = np.arange(6).reshape(2, 3)

a.tofile('out.bin')

b = np.fromfile('out.bin', dtype=a.dtype).reshape(a.shape)

a.tofile('out.txt', sep=',')

b_text = np.fromfile('out.txt', sep=',', dtype=a.dtype).reshape(a.shape)

Limitations include the lack of stored shape or dtype in the file, so reading requires prior knowledge

order
when
the
array
is
flattened
for
writing.
Binary
mode
writes
a
compact
binary
representation
of
the
elements,
without
any
metadata
about
shape
or
dtype.
Text
mode
writes
human-readable
values
but
still
does
not
embed
shape
information
in
the
file.
was
written
in
binary
mode,
specify
the
same
dtype
and
reshape
as
needed.
If
the
file
was
written
in
text
mode,
provide
an
appropriate
sep
to
fromfile
so
the
text
can
be
parsed
back
into
numbers.
of
these
attributes.
For
portable
storage
with
metadata,
NumPy
offers
alternatives
such
as
numpy.save
and
numpy.load,
or
numpy.savetxt
for
text
formats.