Read, save, and share arrays

2.5.5

Choose NumPy binary formats or text files, and preserve format and dtype expectations.

On this page

Store an array with its shape and dtype

Use .npy for one array and .npz to store several named arrays. Load numerical files with allow_pickle=False, and avoid object arrays in files you plan to exchange. Use a context manager when opening .npz archives.

from io import BytesIO
import numpy as np

buffer = BytesIO()
np.save(buffer, np.array([[2, 3]], dtype=np.int16))
buffer.seek(0)
a = np.load(buffer, allow_pickle=False)
print(a.shape, a.dtype.name)
Example output
(1, 2) int16

Read straightforward numeric text

loadtxt suits regularly shaped numeric text. Set the delimiter and skip header rows. Try genfromtxt when you need missing-value handling, or pandas when columns have names, mixed types, or richer parsing needs.

from io import StringIO
import numpy as np

data = StringIO("units,price\n2,3.5\n4,2.0\n")
a = np.loadtxt(data, delimiter=",", skiprows=1)
print(a.tolist())
Example output
[[2.0, 3.5], [4.0, 2.0]]

Official references