NumPy File I/O – Save & Load Arrays

Last Updated: 09 Nov 2025


File I/O lets you save NumPy arrays to disk and load them later — critical for ML models, sensor data, satellite images.

Hinglish Tip:.npy = ek array ka backup. .npz = zip file jisme multiple arrays hain!”


1. np.save() – Save Single Array

import numpy as np

data = np.random.rand(100, 100)
np.save('image.npy', data)    # Saves as .npy (binary)

2. np.load() – Load Single Array

loaded = np.load('image.npy')
print(loaded.shape)           # (100, 100)
print(np.array_equal(data, loaded))  # True

3. np.savez() – Save Multiple Arrays (ZIP)

weights = np.random.rand(10, 5)
bias = np.random.rand(5,)
metadata = np.array(['model_v1', '2025-11-09'])

np.savez('model.npz',
         weights=weights,
         bias=bias,
         info=metadata)

4. np.load() – Load .npz

archive = np.load('model.npz')

print(archive['weights'].shape)   # (10, 5)
print(archive['bias'])
print(archive['info'])

.npz is a dictionary-like object.


5. Compressed: np.savez_compressed()

big = np.random.rand(1000, 1000)
np.savez_compressed('big.npz', data=big)  # ~10x smaller

6. Text Files: np.savetxt() / np.loadtxt()

# Save as CSV
np.savetxt('data.csv', data, delimiter=',', fmt='%.3f')

# Load CSV
loaded_csv = np.loadtxt('data.csv', delimiter=',')

Use only for small, human-readable data.

Load from CSV

# data.csv:
# name,age,salary
# Priya,32,80000
# Amit,27,60000

data = np.genfromtxt('data.csv', delimiter=',', dtype=dt, skip_header=1)
print(data)

7. Use Case: np.savez()

# After training
model = {
    'W1': np.random.rand(784, 128),
    'b1': np.random.rand(128,),
    'W2': np.random.rand(128, 10),
    'b2': np.random.rand(10,)
}

np.savez('mnist_model.npz', **model)

# Later: load and predict
loaded = np.load('mnist_model.npz')
logits = X @ loaded['W1'] + loaded['b1']

8. Binary Raw: tofile() / fromfile()

arr = np.arange(100, dtype=np.float32)
arr.tofile('raw.bin')                  # No header

# Load back
raw = np.fromfile('raw.bin', dtype=np.float32)
print(raw.shape)

Fastest, but no shape info — must know dtype and size.


9. Safety: Always Save Shape

shape = data.shape
np.savez('safe.npz', data=data, shape=shape)

# Load
f = np.load('safe.npz')
data = f['data'].reshape(f['shape'])

|| राम नाम सत्य है ||