Module 6 · Lesson 3
Saving & Loading Arrays
np.save/np.loadwrite a single array to a binary.npyfile.np.savez/np.loadwrite several named arrays to one.npzarchive (loading returns anNpzFileyou index like a dict).np.savetxt/np.loadtxtwrite a plain-text, CSV-like format — human readable, but slower and loses exact dtype information.
All three normally take a file path, but they’re equally happy with an
in-memory file-like object (io.BytesIO for the binary formats,
io.StringIO for text) — handy for round-tripping without touching disk,
which is exactly what the exercises below do. Remember to seek(0) on
the buffer after writing and before reading, since writing leaves the
buffer’s position at the end.
arr = np.array([1, 2, 3, 4])
buf = io.BytesIO()
np.save(buf, arr)
buf.seek(0)
loaded = np.load(buf)
print("single array round-trip:", loaded)
buf2 = io.BytesIO()
np.savez(buf2, first=arr, second=arr * 10)
buf2.seek(0)
archive = np.load(buf2)
print("multi-array round-trip:", archive["first"], archive["second"])
Output:
single array round-trip: [1 2 3 4]
multi-array round-trip: [1 2 3 4] [10 20 30 40]
Round-trip a single array
Write roundtrip_npy(arr) that writes arr to an in-memory io.BytesIO
buffer with np.save, reads it back with np.load, and returns the
loaded array.
💡 Hint
buf = io.BytesIO(), then np.save(buf, arr), then buf.seek(0) before np.load(buf).
✅ Solution
def roundtrip_npy(arr):
buf = io.BytesIO()
np.save(buf, arr)
buf.seek(0)
return np.load(buf)
Round-trip two named arrays
Write roundtrip_npz(a, b) that saves a and b into one in-memory
.npz archive under the keys "a" and "b" with np.savez, reloads it,
and returns a plain dict {"a": ..., "b": ...} of the loaded arrays.
💡 Hint
np.savez(buf, a=a, b=b), buf.seek(0), then np.load(buf) returns an NpzFile — index it with ["a"] and ["b"].
✅ Solution
def roundtrip_npz(a, b):
buf = io.BytesIO()
np.savez(buf, a=a, b=b)
buf.seek(0)
archive = np.load(buf)
return {"a": archive["a"], "b": archive["b"]}