np.load() inspects the file to determine what it actually contains: loading a .npy file returns a single ndarray directly, while loading a .npz file, whether compressed or not, returns a dict-like NpzFile object exposing each saved array by the name it was given. By default, allow_pickle=False refuses to load files containing pickled Python objects, as opposed to plain numeric array data, a deliberate security measure, since unpickling data from an untrusted source can execute arbitrary code.
1Understanding np.load()
np.load() inspects the file to determine what it actually contains: loading a .npy file returns a single ndarray directly, while loading a .npz file, whether compressed or not, returns a dict-like NpzFile object exposing each saved array by the name it was given. By default, allow_pickle=False refuses to load files containing pickled Python objects, as opposed to plain numeric array data, a deliberate security measure, since unpickling data from an untrusted source can execute arbitrary code.
Only set allow_pickle=True when you specifically trust the source of the file and know it needs to contain pickled Python objects — loading a file with pickling enabled from an untrusted source is a genuine security risk, since unpickling can execute arbitrary code.
import numpy as np
arr = np.array([10, 20, 30])
np.save("numbers.npy", arr)
loaded = np.load("numbers.npy")
print(loaded)
print(type(loaded))2Practical Example
Here is a real-world application of np.load() showing how it is used in production NumPy code.
import numpy as np
np.savez("bundle.npz", a=np.array([1, 2]), b=np.array([3, 4]))
with np.load("bundle.npz") as data:
print(data["a"])
print(data["b"])3Best Practices
Follow these guidelines when working with np.load():
1. Leave allow_pickle at its default of False unless you specifically know the file needs it, to avoid a real security risk from untrusted files
2. Check whether a loaded object is a plain ndarray, from .npy, or an NpzFile, from .npz, if your code needs to handle both possibilities
3. Close an NpzFile object explicitly, or load it inside a with block, once you're done reading from it, the same as you would for a regular file
Tip: Only set allow_pickle=True when you specifically trust the source of the file and know it needs to contain pickled Python objects — loading a file with pickling enabled from an untrusted source is a genuine security risk, since unpickling can execute arbitrary code.
import numpy as np
arr = np.array([10, 20, 30])
np.save("numbers.npy", arr)
loaded = np.load("numbers.npy")
print(loaded)
print(type(loaded))