0
0
NumpyHow-ToBeginner ยท 3 min read

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.load causes an error because it expects a binary .npy or .npz file.
  • For text files, forgetting to specify the correct delimiter in np.loadtxt can lead to wrong data parsing.
  • Loading pickled objects with allow_pickle=False will raise an error; set allow_pickle=True only 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

FunctionUse CaseFile TypeKey Parameter
numpy.loadLoad binary array file.npy or .npzallow_pickle (default False)
numpy.loadtxtLoad text array fileText files (csv, txt)delimiter (default whitespace)
numpy.savetxtSave array to text fileText filesdelimiter
numpy.saveSave array to binary file.npyNone
โœ…

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.