Page10/12
File I/O & Data Persistence · Page 1 of 1
Saving & Loading Arrays
File I/O & Data Persistence
Binary Formats (.npy & .npz)
Fast, efficient storage designed specifically for NumPy:
# Save single array
np.save('data.npy', arr)
arr = np.load('data.npy')
# Save multiple arrays (compressed)
np.savez_compressed('data.npz',
features=X,
labels=y)
# Load from .npz
loaded = np.load('data.npz')
X = loaded['features']
y = loaded['labels']
Advantages of .npy/.npz
- Fast (binary format)
- Preserves dtype (int32 stays int32)
- Preserves shape (no ambiguity)
- Compressed option available
Text Formats (CSV, TSV)
Human-readable, shareable:
# Save as CSV
np.savetxt('data.csv', arr, delimiter=',')
# Load from CSV
arr = np.loadtxt('data.csv', delimiter=',')
When to Use Each
| Format | Speed | Size | Human-Readable |
|---|---|---|---|
| .npy | ⚡⚡⚡ | Medium | ❌ |
| .npz | ⚡⚡⚡ | Small | ❌ |
| CSV | ⚡ | Large | ✅ |
| TSV | ⚡ | Large | ✅ |
Production tip: Use .npz for internal storage, CSV for sharing with non-Python tools.
main.py
Loading...
OUTPUT
▶Click "Run Code" to execute…