NumPy: File I/O

Last updated: 2026-08-26

1. What You'll Learn



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 only
Loaded: [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 only
Loaded 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 only
Keys: ['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



📝 Exercises

  1. Beginner (Difficulty ⭐): Create an array, save it as .npy and .csv, load both back, and compare the loaded values.

  2. Intermediate (Difficulty ⭐⭐): Create 3 arrays, save them in a single .npz file, load them back, and verify each array is correctly restored.

  3. 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.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏