Save Array to File & Read Array from File – NumPy

NumPy – Save array to file & read 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)

Examples

1. Save numpy 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
Copy

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.

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)
Copy

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, we learned how to save a numpy array to a file, and load the numpy array from file to an object in the program.

Related Tutorials

Code copied to clipboard successfully 👍