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, the savez() method will save arrays to the argument file after the arr_0, arr_1, and so on.
  • If arrays are specified to **kwds, then savez() 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 names arr_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 modules
import numpy as np
import tempfile as file
# create a temporary file in local storage
outfile = file.TemporaryFile()
# creating four random arrays
x1 = 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() method
np.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 program
npzfile = np.load(outfile)
# print 'a' to 'd' arrays
print("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 to outfile.
  • Lines 9–12: We create four random arrays: x1, x2, x3, and x4.
  • Line 15: The np.savez(outfile, a = x1, b = x2, c = x3, d = x4) command saves x1, x2, x3, and x4 as a, b, c, and d in outfile in .npz format.
  • 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 specified outfile from memory to program.
  • Lines 24–27: We print arrays from the loaded .npz file.

Free Resources