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'])
.npzis 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. Generate From text
- Load CSV / text files even when they are messy (missing values, comments, etc.)
# data.csv
# name, age, height, score
# Amit, 25, 1.65, 95
# Suraj, , 1.80, 87
# Raj, 30, 1.75,
# Avi, 22, 1.70, 99
data = np.genfromtxt('data.csv',
delimiter=',', # comma separated
skip_header=1, # skip first line
dtype=None, # auto detect types
encoding='utf-8',
filling_values=np.nan) # missing → nan
print(data)
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
dtypeand 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'])
|| राम नाम सत्य है ||