How to Load Array from File Using NumPy
To load an array from a file in NumPy, use
numpy.load for binary files (.npy) or numpy.loadtxt for text files. These functions read the file and return the array stored inside.Syntax
numpy.load(file, allow_pickle=False): Loads arrays from a binary .npy or .npz file. file is the filename or file object. allow_pickle controls if loading pickled objects is allowed (default is False for safety).
numpy.loadtxt(fname, delimiter=None): Loads arrays from a text file. fname is the filename or file object. delimiter specifies the character separating values (default is whitespace).
python
import numpy as np # Load from binary .npy file array = np.load('data.npy') # Load from text file array_text = np.loadtxt('data.txt', delimiter=',')
Example
This example shows how to save a NumPy array to a file and then load it back using np.save and np.load. It also shows loading from a text file using np.savetxt and np.loadtxt.
python
import numpy as np # Create an array arr = np.array([[1, 2, 3], [4, 5, 6]]) # Save array to binary file np.save('array.npy', arr) # Load array from binary file loaded_arr = np.load('array.npy') print('Loaded from .npy file:') print(loaded_arr) # Save array to text file np.savetxt('array.txt', arr, delimiter=',') # Load array from text file loaded_txt_arr = np.loadtxt('array.txt', delimiter=',') print('\nLoaded from text file:') print(loaded_txt_arr)
Output
Loaded from .npy file:
[[1 2 3]
[4 5 6]]
Loaded from text file:
[[1. 2. 3.]
[4. 5. 6.]]
Common Pitfalls
- Trying to load a text file with
np.loadcauses an error because it expects a binary .npy or .npz file. - For text files, forgetting to specify the correct
delimiterinnp.loadtxtcan lead to wrong data parsing. - Loading pickled objects with
allow_pickle=Falsewill raise an error; setallow_pickle=Trueonly if you trust the file source.
python
import numpy as np # Wrong: loading text file with np.load (raises error) # np.load('array.txt') # Uncommenting this line will cause an error # Correct: use np.loadtxt for text files arr = np.loadtxt('array.txt', delimiter=',') print(arr)
Output
[[1. 2. 3.]
[4. 5. 6.]]
Quick Reference
| Function | Use Case | File Type | Key Parameter |
|---|---|---|---|
| numpy.load | Load binary array file | .npy or .npz | allow_pickle (default False) |
| numpy.loadtxt | Load text array file | Text files (csv, txt) | delimiter (default whitespace) |
| numpy.savetxt | Save array to text file | Text files | delimiter |
| numpy.save | Save array to binary file | .npy | None |
Key Takeaways
Use numpy.load to read binary .npy files and numpy.loadtxt for text files.
Always specify the correct delimiter when loading text files with numpy.loadtxt.
Do not use numpy.load on text files; it only works with binary .npy or .npz files.
Set allow_pickle=True in numpy.load only if you trust the file source.
Saving arrays with numpy.save and numpy.savetxt helps prepare files for loading.