What is the savez() method in NumPy?
Overview
The savez() method is used to save multiple arrays into a single file in uncompressed .npz format. It takes arrays as keyword arguments to save them into the specified file.
- If arrays are specified to
*args, thesavez()method will save arrays to the argument file after thearr_0,arr_1, and so on. - If arrays are specified to
**kwds, thensavez()will save arrays to the corresponding file as defined array names.
Syntax
numpy.savez(file, *args, **kwds)
Parameters
file: This can be a filename as a string or a file-like object.*args: These are arrays as arguments to save in a specified file. Such arrays are saved in the file with namesarr_0,arr_1, and so on.**kwds: These are arrays as keyword arguments to save in a file with the keyword as the array name.
Return value
It does not return anything.
Example
# import numpy and tempfile modulesimport numpy as npimport tempfile as file# create a temporary file in local storageoutfile = file.TemporaryFile()# creating four random arraysx1 = np.random.randint(0, 20, 10)x2 = np.random.randint(0, 50, 10)x3 = np.random.randint(0, 100, 10)x4 = np.random.randint(10, 100, 10)# invoking savez() methodnp.savez(outfile, a = x1, b = x2, c = x3, d = x4)# Required to simulate the closing and reopening file_ = outfile.seek(0)# It'll load pickled objects or .npy, .npz file in programnpzfile = np.load(outfile)# print 'a' to 'd' arraysprint("a =", npzfile['a'])print("b =", npzfile['b'])print("c =", npzfile['c'])print("d =", npzfile['d'])
Explanation
- Line 6: The
TemporaryFile()method creates a temporary memory and returns a path-like object tooutfile. - Lines 9–12: We create four random arrays:
x1,x2,x3, andx4. - Line 15: The
np.savez(outfile, a = x1, b = x2, c = x3, d = x4)command savesx1,x2,x3, andx4asa,b,c, anddinoutfilein.npzformat. - Line 18: We stimulate the file handler after closing and reopening the file using
outfile.seek(0). - Line 21: We use
np.load()to load the specifiedoutfilefrom memory to program. - Lines 24–27: We print arrays from the loaded
.npzfile.