NumPy: File I/O
Last updated: 2026-08-26
1. What You'll Learn
- ❶ Saving and loading
.npyfiles (single array) - ❷ Saving and loading
.npzfiles (multiple arrays) - ❸ CSV/text file I/O with
loadtxtandsavetxt - ❹ Memory-mapped arrays for large datasets
2. Key Concepts
(1) .npy Format
PYTHON
import numpy as np
a = np.array([1, 2, 3, 4, 5])
# Save
np.save('array.npy', a)
# Load
b = np.load('array.npy')
print(b) # [1 2 3 4 5]
(2) .npz Format (Multiple Arrays)
PYTHON
x = np.array([1, 2, 3])
y = np.array([4, 5, 6])
# Save multiple arrays
np.savez('data.npz', x=x, y=y)
# Load
data = np.load('data.npz')
print(data['x']) # [1 2 3]
print(data['y']) # [4 5 6]
(3) CSV/Text Files
PYTHON
# Save to CSV
data = np.array([[1, 2, 3],
[4, 5, 6]])
np.savetxt('data.csv', data, delimiter=',', fmt='%.2f')
# Load from CSV
loaded = np.loadtxt('data.csv', delimiter=',')
▶ Example: Saving and loading .npy files (Difficulty ⭐)
PYTHON
import numpy as np
import os
# Create and save an array
a = np.array([1, 2, 3, 4, 5])
np.save('example.npy', a)
# Load it back
b = np.load('example.npy')
print("Loaded:", b)
print("Same data:", np.array_equal(a, b))
# Clean up
os.remove('example.npy')
Output:
TEXT 📖 Display onlyLoaded: [1 2 3 4 5] Same data: True
▶ Example: CSV file I/O (Difficulty ⭐⭐)
PYTHON
import numpy as np
import os
data = np.array([[1.5, 2.3, 3.7],
[4.1, 5.6, 6.2],
[7.8, 8.4, 9.9]])
# Save to CSV
np.savetxt('data.csv', data, delimiter=',', fmt='%.2f',
header='x,y,z', comments='')
# Load from CSV
loaded = np.loadtxt('data.csv', delimiter=',')
print("Loaded CSV:\n", loaded)
# Load specific columns
col_0 = np.loadtxt('data.csv', delimiter=',', usecols=0)
print("First column:", col_0)
os.remove('data.csv')
Output:
TEXT 📖 Display onlyLoaded CSV: [[1.5 2.3 3.7] [4.1 5.6 6.2] [7.8 8.4 9.9]] First column: [1.5 4.1 7.8]
▶ Example: Working with .npz files (Difficulty ⭐⭐)
PYTHON
import numpy as np
import os
x = np.linspace(0, 10, 100)
y = np.sin(x)
z = np.cos(x)
# Save multiple arrays
np.savez('trig.npz', x=x, y=y, z=z)
# Load and access by name
data = np.load('trig.npz')
print("Keys:", list(data.keys()))
print("x[:5]:", data['x'][:5])
print("y[:5]:", data['y'][:5])
os.remove('trig.npz')
Output:
TEXT 📖 Display onlyKeys: ['x', 'y', 'z'] x[:5]: [0. 0.1010101 0.2020202 0.3030303 0.4040404] y[:5]: [0. 0.10083842 0.20064886 0.2984138 0.3931366]
❓ FAQ
Q What's the advantage of .npy over CSV?
A .npy preserves dtype exactly, is faster to read/write, and takes less disk space. CSV is human-readable and portable but slower and loses dtype information.
Q What is a memory-mapped array?
A
np.load('file.npy', mmap_mode='r') loads the file as a memory-mapped array — it doesn't load the entire file into memory at once. Useful for datasets larger than RAM.Q How do I handle missing values in CSV?
A Use
np.genfromtxt with filling_values parameter to specify a default for missing entries.📖 Summary
np.save/np.load: single array in .npy format (fast, compact, dtype-preserving)np.savez/np.load: multiple arrays in .npz format (compressed dictionary)np.savetxt/np.loadtxt: CSV/text file I/Onp.genfromtxt: handles missing values and mixed types- Memory-mapped arrays:
mmap_mode='r'for large datasets
📝 Exercises
-
Beginner (Difficulty ⭐): Create an array, save it as .npy and .csv, load both back, and compare the loaded values.
-
Intermediate (Difficulty ⭐⭐): Create 3 arrays, save them in a single .npz file, load them back, and verify each array is correctly restored.
-
Advanced (Difficulty ⭐⭐⭐): Create a large array (1000x1000), save it as .npy, and load it with
mmap_mode='r'. Access a single element and explain why this is more memory-efficient for large datasets.