NumPy Tutorial NumPy Statistics NumPy References

NumPy - save() function



The NumPy save() function is used to save an array to a binary file in NumPy .npy format.

Note: To load arrays from .npy file, load() function is used.

Syntax

numpy.save(file, arr)

Parameters

file Required. Specify file or filename to which the data is saved. If file is a file-object, then the filename is unchanged. If file is a string or Path, a .npy extension will be appended to the filename if it does not already have one.
arr Required. Specify array data to be saved.

Return Value

None.

Example:

In the example below, array arr is saved into a new binary file called test.npy. Further, the load() function is used to load the saved array from the file and print it

import numpy as np

arr = np.array([10, 20, 30, 40, 50, 60])

#saving arr in binary file - test.npy
np.save("test", arr)

#loading array from test.npy
y = np.load("test.npy")

#displaying the content of y
print(y)

The output of the above code will be:

[10 20 30 40 50 60]

Example:

Lets assume that we have a file called demo.npy. The example below describes how to save numpy arrays in it and load the saved arrays from it.

import numpy as np

#open the file in write mode 
#to save numpy arrays
MyFile = open("demo.npy", "wb")
np.save(MyFile, np.array([10, 20]))
np.save(MyFile, np.array([10, 30]))
MyFile.close()

#open the file to read contant
MyFile = open("demo.npy", "rb")
x = np.load(MyFile)
y = np.load(MyFile)
MyFile.close()

#displaying the content of x and y
print(x)
print(y)

The output of the above code will be:

[10 20]
[10 30]

❮ NumPy - Functions