Python Numpy – Save Array to File & Read Array from File

Save Numpy Array to File & Read Numpy Array from File

You can save numpy array to a file using numpy.save() and then later, load into an array using numpy.load().

Following is a quick code snippet where we use firstly use save() function to write array to file. Secondly, we use load() function to load the file to a numpy array.

# save array to file
numpy.save(file, array)
# load file to array
array = numpy.load(file)

Example 1: Save the Array to File

In the following example: we will initialize an array; create and open a file in write binary mode; and then write the array to the file using numpy.save() method.

Python Program

import numpy as np

#initialize an array
arr = np.array([[[11, 11, 9, 9],
                  [11, 0, 2, 0]
				 ],
	             [[10, 14, 9, 14],
                  [0, 1, 11, 11]]])

# open a binary file in write mode
file = open("arr", "wb")
# save array to the file
np.save(file, arr)
# close the file
file.close

Once you are done saving the array, do not forget to close the file.

You should observe that a new file named arr is created in your current working directory. Extension to the file is not required. But you may use an extension of your choice.

Example 2: Load the saved numpy array from file

In this example, we will load the array from file. We will use the above example to save an array and continue that to read the array from file.

Python Program

import numpy as np

#initialize an array
arr = np.array([[[11, 11, 9, 9],
                  [11, 0, 2, 0]
				 ],
	             [[10, 14, 9, 14],
                  [0, 1, 11, 11]]])

# open a binary file in write mode
file = open("arr", "wb")
# save array to the file
np.save(file, arr)
# close the file
file.close

# open the file in read binary mode
file = open("arr", "rb")
#read the file to numpy array
arr1 = np.load(file)
#close the file
print(arr1)

Output

[[[11 11  9  9]
  [11  0  2  0]]

 [[10 14  9 14]
  [ 0  1 11 11]]]

We have successfully read the numpy array from file and load an object with this array.

Summary

In this Numpy Tutorial of Python Examples, we learned how to save a numpy array to a file, and load the numpy array from file to an object in the program.