This article will discuss saving and reading a NumPy array to and from a binary file.
The NumPy tofile() function allows you to save an array to a text or binary file. Since we are interested in binary files, let us learn how we can use this function.
The function syntax is as shown:
ndarray.tofile(fid, sep='', format='%s')
The function parameters are as illustrated below:
- fid – refers to an open file object or path to file.
- sep – specifies the separator between the array items. For binary files, this is equal to file.write(a.tobytes()) where a is the input array.
- Format – specifies the format string for text file output.
An example is as shown below:
# import numpy
import numpy as np
from numpy.random import default_rng
arr = default_rng(24).random((3,5,3))
In the example above, we have a simple program that generates an array using the random function.
The resulting array is as shown:
To save the array to a binary file using the tofile() function, we can do this:
This should create a new binary file holding the input array.
To load the data stored in a binary file, we can use the fromfile function. The function has a syntax as shown:
numpy.fromfile(file, dtype=float, count=- 1, sep='', offset=0, *, like=None)
Check the docs for more info.
In the example, to load the file, we can run:
load_arr = np.fromfile('arr.bin')
This should return the array stored in the binary file.