Python

Numpy Fromfile

This article will discuss saving and reading a NumPy array to and from a binary file.

NumPy tofile()

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:

1
ndarray.tofile(fid, sep='', format='%s')

The function parameters are as illustrated below:

  1. fid – refers to an open file object or path to file.
  2. 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.
  3. Format – specifies the format string for text file output.

An example is as shown below:

1
2
3
4
5
# import numpy
import numpy as np
from numpy.random import default_rng
arr =  default_rng(24).random((3,5,3))
arr

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:

1
arr.tofile('arr.bin')

This should create a new binary file holding the input array.

NumPy fromfile

To load the data stored in a binary file, we can use the fromfile function. The function has a syntax as shown:

1
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:

1
2
load_arr = np.fromfile('arr.bin')
display(arr)

This should return the array stored in the binary file.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list