/Curriculum/AdvancedI/O & Persistence

37. NumPy File HandlingIntermediate

Save and load binary .npy/.npz archives and load text CSV datasets with loadtxt().

14 mins

Concept Overview

NumPy supports high-speed binary serialization using `.npy` (single array) and compressed `.npz` (multi-array archives), preserving exact shapes and dtypes.

Hardware Mental Model

Saving to CSV writes numbers as slow human-readable text characters. Saving to `.npy` dumps raw binary bytes directly from RAM to disk, loading 10x faster.

Key Concepts (1)Click snippet to load in editor

`.npy` stores data in native binary format with shape/dtype metadata headers. It loads 10x faster and requires 50% less disk space than CSV.

np.save('data.npy', arr); loaded = np.load('data.npy')

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:np.savetxt('data.csv', arr) # Default format is scientific notation e.g. 1.000000000000000000e+01
✓ Correct:np.savetxt('data.csv', arr, fmt='%d', delimiter=',')

Specify `fmt='%d'` for integers and `delimiter=','` for clean CSV output.

Pro Tip: Use binary `.npy` for internal storage and `savetxt` only when sharing with non-Python tools.

📌 Quick Revision

Core takeaway points from this topic
`np.save('file.npy', arr)`: Saves single array to binary file.
`np.load('file.npy')`: Loads array back into memory.
`np.savez('file.npz', a=arr1, b=arr2)`: Saves multiple arrays in one file.
`np.savetxt()` / `np.loadtxt()`: Reads and writes text CSV files.
Editor: 37. NumPy File Handling
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Save and Load Binary Array

Create `arr = np.array([100, 200, 300])`, save it to `'test.npy'` with `np.save`, load it with `np.load`, and print.

Expected Output Target:[100 200 300]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state