The numpy.load()
is used to load arrays or pickled objects from files with .npy
, and .npz
extensions to volatile memory or program.
Pickling is a process in which Python objects are converted into streams of bytes to store data in file. Therefore, it results in a packed object.
numpy.load(file, mmap_mode=None, allow_pickle=False, fix_imports=True,encoding='ASCII')
It takes the following argument values:
file
: This is the file to read. It can be either a pathlib.Path
or a file-like
object or a string.mmap_mode
: The default value of this parameter is None
. Other possible values are '+'
, 'r'
, 'w+'
, and 'c'
. It follows the specified memory mapping mode when set to any of these values.allow_pickle
: When set to True
, it will allow reading pickle arrays from .npy
and .npz
files. The default value of this parameter is False
.fix_imports
: This parameter is useful when we load pickles generated from the older versions of Python. The default value of this parameter is True
.encoding
: It is used to select the pickle file reading encoding scheme. The default value of this parameter is 'ASCII'
.It returns the data stored in the files as an array, tuple, dict, and so on.
It also raises the following exceptions.
OSError
: It returns this error when the file is inaccessible or unreadable.UnpicklingError
: It returns this error if allow_pickle
is set, but the file cannot be loaded in the program.ValueError
: It returns this error when a specified file contains an array type object, but allow_pickle
is set to False
.In the code snippet below, let's look at how the load()
function loads an array or pickle file from memory.
# Program to show numpy.load() working# loading numpy library as alias npimport numpy as np# creating a numpy arrayarray = np.array([3,4,51,6,70,8,9,34,56,7,89,87,])# print array on consoleprint("array is:", array)# save array in .npy file as data.npynp.save('data', array)print("the array is saved in the file data.npy")# loading data.npy file data in array2array2 = np.load('data.npy')# print loaded data on consoleprint("array2 is:", array2)
data.npy
using np.save()
. If the .npy
extension is not specified at the end of the filename it will append it by default.np.load()
function to load contents from the data.npy
file in the program as array2
.array2
on the console to show the loaded data from the data.npy
file.