Save computed arrays
Persisting numerical results between program runs
NumPy · Function
Saves array-like data to NumPy’s binary .npy format. It accepts paths or file objects and optionally permits pickle serialization for object arrays.
The function serializes array-like data into NumPy's binary .npy format. A path-like filename receives the .npy suffix when needed, while a file object keeps its existing name; object arrays may be written through Python pickling when allowed.
numpy.save(file, arr, allow_pickle=True)| Name | Type | Description |
|---|---|---|
file | file, str, or pathlib.Path | File or filename to which the data is saved. A file object, string, or pathlib.Path is accepted; a suffix may be added for path-based names. |
arr | array_like | Array data to be saved. |
allow_pickle | bool, optional | Whether object arrays may be saved using Python pickles. Default: True. |
import os
import tempfile
import numpy as np
with tempfile.TemporaryDirectory() as directory:
path = os.path.join(directory, "values")
values = np.array([[1, 2], [3, 4]])
np.save(path, values)
restored = np.load(path + ".npy")
print(restored)Creates a two-dimensional array, saves it as values.npy, and loads it back.
Persisting numerical results between program runs
Exchanging ndarray data between Python processes
Writing several array records to one stream
np.save writes array-like data in NumPy's binary .npy format. With a string or Path, NumPy adds .npy if the name does not already have that extension.
Follow-up: What happens with an already-open file object? Its filename is unchanged, and successive saves append data to the file.
file accepts a file object, string, or pathlib.Path, while arr accepts array-like data. allow_pickle controls whether object arrays can be saved using Python pickles and defaults to True.
Follow-up: Why might allow_pickle be False? Pickle loading can execute arbitrary code, and pickled objects can be less portable across Python installations.
The function's documented effect is writing the array to a .npy file; the page does not document a return value, so it returns None. The format preserves NumPy array data for later loading.
Follow-up: How can multiple arrays be stored in one file? Use an open file object and call np.save repeatedly; each saved record is appended.
numpy.loadnumpy.saveznumpy.savez_compressed