Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 19

Saving and Loading Arrays

Save arrays to text and CSV with savetxt, read them with loadtxt and genfromtxt, keep exact arrays in .npy and .npz files, and load JSON.

Intermediate25 min
Saving and Loading Arrays hero Module 23 Lesson 19

Text files are easy to read and share. Binary .npy files keep the dtype and shape exactly and load faster. In the playground, files live in browser memory and disappear when the page reloads.

Which NumPy function reads and writes which kind of file

Text files

np.savetxt writes one row per line. fmt="%d" writes whole numbers. np.loadtxt reads floats by default, so pass dtype=int to get integers back.

python
import numpy as np

data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
np.savetxt("grid.txt", data, fmt="%d", delimiter=" ")

with open("grid.txt", encoding="utf-8") as file:
    print(file.read())

print(np.loadtxt("grid.txt"))
print(np.loadtxt("grid.txt", dtype=int))

Output:

text
1 2 3
4 5 6
7 8 9

[[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]]
[[1 2 3]
 [4 5 6]
 [7 8 9]]

CSV with a header

Use a comma delimiter and a header line. comments="" stops NumPy from putting # in front of the header. When reading, skiprows=1 skips it.

python
import numpy as np

scores = np.array([[1, 88.5], [2, 91.0], [3, 76.5]])
np.savetxt("scores.csv", scores, fmt=["%d", "%.1f"], delimiter=",",
           header="id,score", comments="")

with open("scores.csv", encoding="utf-8") as file:
    print(file.read())

loaded = np.loadtxt("scores.csv", delimiter=",", skiprows=1)
print(loaded[:, 1].mean())

Output:

text
id,score
1,88.5
2,91.0
3,76.5

85.33333333333333

Mixed columns with genfromtxt

loadtxt wants every column to be a number. np.genfromtxt with names=True and dtype=None reads the header as column names and picks a type for each column, so text and numbers can sit side by side.

python
import csv

import numpy as np

rows = [["id", "product", "price"], [1, "desk lamp", 24.5], [2, "notebook", 3.2], [3, "backpack", 41.0]]
with open("products.csv", "w", newline="", encoding="utf-8") as file:
    csv.writer(file).writerows(rows)

table = np.genfromtxt("products.csv", delimiter=",", names=True, dtype=None, encoding="utf-8")
print(table["product"])
print(table["price"].sum())

Output:

text
['desk lamp' 'notebook' 'backpack']
68.7

Binary .npy and .npz

np.save writes one array to a .npy file, and np.load gives it back with the same dtype and shape. np.savez stores several arrays by name in one .npz file.

python
import numpy as np

data = np.arange(6, dtype=np.int16).reshape(2, 3)
np.save("data.npy", data)
back = np.load("data.npy")
print(back, back.dtype, back.shape)

np.savez("bundle.npz", inputs=data, labels=np.array([0, 1]))
bundle = np.load("bundle.npz")
print(sorted(bundle.files))
print(bundle["labels"])

Output:

text
[[0 1 2]
 [3 4 5]] int16 (2, 3)
['inputs', 'labels']
[0 1]

JSON

json.load gives Python lists. Pass a list of numbers to np.array to get an array.

python
import json

import numpy as np

with open("readings.json", "w", encoding="utf-8") as file:
    json.dump({"station": "north", "values": [[12, 15], [14, 18]]}, file)

with open("readings.json", encoding="utf-8") as file:
    record = json.load(file)

values = np.array(record["values"])
print(record["station"], values.shape, values.mean())

Output:

text
north (2, 2) 14.75

Key takeaways

  • savetxt and loadtxt handle numeric text and CSV

  • genfromtxt with names=True reads mixed columns by name

  • .npy keeps one array exactly, and .npz keeps several

  • Playground files disappear when the page reloads

  • Next: What Is pandas — labelled tables built on arrays

  • Previous: Linear Algebra

Loading playground…

Check your understanding

Saving and Loading Arrays Quiz

What does np.savetxt write?

1 / 10