How to Save Array to File in NumPy: Simple Guide
You can save a NumPy array to a file using
np.save('filename.npy', array) for binary format or np.savetxt('filename.txt', array) for text format. These functions store the array data so you can load it later with np.load or read the text file.Syntax
np.save(filename, array): Saves the array in a binary .npy file for efficient storage and fast loading.
np.savetxt(filename, array): Saves the array in a human-readable text file, useful for simple data or sharing.
filename: String with the file name or path.
array: The NumPy array you want to save.
python
import numpy as np # Save array in binary format np.save('data.npy', np.array([1, 2, 3])) # Save array in text format np.savetxt('data.txt', np.array([[1, 2], [3, 4]]))
Example
This example shows how to save a NumPy array to a binary file and a text file, then load them back to verify the data.
python
import numpy as np # Create an array arr = np.array([[10, 20, 30], [40, 50, 60]]) # Save as binary file np.save('array.npy', arr) # Save as text file np.savetxt('array.txt', arr, fmt='%d') # Load binary file loaded_arr = np.load('array.npy') # Load text file loaded_txt = np.loadtxt('array.txt', dtype=int) print('Loaded from .npy file:') print(loaded_arr) print('\nLoaded from .txt file:') print(loaded_txt)
Output
Loaded from .npy file:
[[10 20 30]
[40 50 60]]
Loaded from .txt file:
[[10 20 30]
[40 50 60]]
Common Pitfalls
- Using
np.savetxtfor arrays with more than 2 dimensions will cause errors because it only supports 1D or 2D arrays. - Saving with
np.saveadds a.npyextension automatically if not provided; forgetting this can cause confusion when loading. - Text files saved with
np.savetxtlose some precision and metadata compared to binary files.
python
import numpy as np arr_3d = np.ones((2, 2, 2)) # Wrong: np.savetxt does not support 3D arrays # np.savetxt('3d.txt', arr_3d) # This will raise an error # Right: Use np.save for 3D arrays np.save('3d.npy', arr_3d) # Loading works with np.load loaded_3d = np.load('3d.npy') print(loaded_3d)
Output
[[[1. 1.]
[1. 1.]]
[[1. 1.]
[1. 1.]]]
Quick Reference
| Function | Purpose | File Format | Supports Multi-D Arrays |
|---|---|---|---|
| np.save(filename, array) | Save array in binary format | .npy | Yes |
| np.savetxt(filename, array) | Save array in text format | .txt or .csv | Only 1D or 2D |
Key Takeaways
Use np.save to store arrays in efficient binary .npy files for any shape.
Use np.savetxt to save arrays as readable text files but only for 1D or 2D arrays.
Always load saved arrays with np.load for .npy files and np.loadtxt for text files.
Remember np.save adds .npy extension automatically if missing.
Avoid np.savetxt for arrays with more than two dimensions to prevent errors.