Skip to content
NumPy

Saving and Loading

Persist arrays with .npy, .npz, and text formats.

By EZ4Code Team
iopersistence

Code

import numpy as np

a = np.arange(10)
b = np.random.rand(3, 3)

# Single array
np.save("a.npy", a)
loaded = np.load("a.npy")

# Multiple arrays
np.savez("multi.npz", a=a, b=b)
data = np.load("multi.npz")
print(data["a"], data["b"])

# Compressed
np.savez_compressed("multi.npz", a=a, b=b)

# Text formats
np.savetxt("a.csv", b, delimiter=",", fmt="%.4f")
from_file = np.loadtxt("a.csv", delimiter=",")

Explanation

save and load handle single arrays in the binary .npy format, while savez bundles several arrays into a .npz archive that loads like a dict. savez_compressed shrinks storage at the cost of CPU. savetxt and loadtxt exchange data in human-readable CSV or whitespace formats.

More NumPy Snippets