0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.save and np.load in NumPy for Saving and Loading Arrays

Use np.save(filename, array) to save a NumPy array to a binary file with a .npy extension. Load the saved array back into memory using np.load(filename), which reads the file and returns the original array.
๐Ÿ“

Syntax

np.save saves a single NumPy array to a file in binary format. file is the file path (string), and arr is the NumPy array to save.

np.load loads the array back from the file. It takes file as input and returns the saved array.

python
np.save(file, arr, allow_pickle=True, fix_imports=True)
np.load(file, allow_pickle=True, fix_imports=True, mmap_mode=None)
๐Ÿ’ป

Example

This example shows how to save a NumPy array to a file named 'data.npy' and then load it back into a new variable.

python
import numpy as np

# Create a sample array
arr = np.array([10, 20, 30, 40, 50])

# Save the array to a file
np.save('data.npy', arr)

# Load the array from the file
loaded_arr = np.load('data.npy')

print('Original array:', arr)
print('Loaded array:', loaded_arr)
Output
Original array: [10 20 30 40 50] Loaded array: [10 20 30 40 50]
โš ๏ธ

Common Pitfalls

  • For np.save, always include the .npy extension in the filename to avoid confusion.
  • When loading, if the file does not exist or the path is wrong, np.load will raise a FileNotFoundError.
  • By default, np.save allows saving Python objects with allow_pickle=True, but be cautious when loading files from untrusted sources due to security risks.
  • Trying to save multiple arrays with np.save will overwrite the file; use np.savez for multiple arrays.
python
import numpy as np

arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])

# Wrong: This overwrites the file
np.save('arrays.npy', arr1)
np.save('arrays.npy', arr2)  # arr1 is lost

# Right: Use np.savez to save multiple arrays
np.savez('arrays.npz', arr1=arr1, arr2=arr2)

loaded = np.load('arrays.npz')
print(loaded['arr1'])
print(loaded['arr2'])
Output
[1 2 3] [4 5 6]
๐Ÿ“Š

Quick Reference

FunctionPurposeKey Parameters
np.saveSave a single NumPy array to a .npy filefile: filename, arr: array to save
np.loadLoad a NumPy array from a .npy filefile: filename to load from
np.savezSave multiple arrays to a compressed .npz filefile: filename, named arrays as kwargs
np.load (for .npz)Load multiple arrays from a .npz fileReturns a dict-like object with arrays
โœ…

Key Takeaways

Use np.save with a filename ending in .npy to save a single array.
Use np.load with the filename to load the saved array back into memory.
Always check file paths to avoid FileNotFoundError when loading.
Use np.savez to save multiple arrays in one file without overwriting.
Be cautious with allow_pickle=True when loading files from unknown sources.