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:
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:
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:
Check the docs for more info.
In the example, to load the file, we can run:
This should return the array stored in the binary file.