We use np.save() and np.load() to save and load numpy arrays quickly in a compact binary format. This helps keep data safe and easy to reuse.
0
0
np.save() and np.load() for binary in NumPy
Introduction
You want to save a large array to disk and load it later without losing data.
You need to share numpy arrays between programs or sessions efficiently.
You want to save intermediate results during data processing to avoid recalculating.
You want to store arrays in a format that loads faster than text files.
You want to keep array data in a file that preserves data types exactly.
Syntax
NumPy
np.save(filename, array) np.load(filename)
filename should be a string ending with .npy or without extension (it adds .npy automatically).
np.save() saves one array; for multiple arrays, use np.savez().
Examples
Saves a simple 1D array to a file named
my_array.npy.NumPy
import numpy as np arr = np.array([1, 2, 3]) np.save('my_array.npy', arr)
Loads the saved array from the file and prints it.
NumPy
loaded_arr = np.load('my_array.npy') print(loaded_arr)
If you omit the extension,
.npy is added automatically.NumPy
np.save('data', arr) # saves as 'data.npy'
Sample Program
This program creates a 2D numpy array, saves it to a binary file named saved_array.npy, then loads it back and prints it. This shows how to keep data between program runs.
NumPy
import numpy as np # Create a 2D array array_to_save = np.array([[10, 20, 30], [40, 50, 60]]) # Save the array to a binary file np.save('saved_array.npy', array_to_save) # Load the array back from the file loaded_array = np.load('saved_array.npy') # Print the loaded array print(loaded_array)
OutputSuccess
Important Notes
The saved file is in a binary format, so it is not human-readable but loads very fast.
Use np.savez() if you want to save multiple arrays in one file.
Make sure to use the same numpy version when saving and loading to avoid compatibility issues.
Summary
np.save() saves one numpy array to a binary file.
np.load() loads the saved array back into memory.
This method is fast and preserves data types exactly.