NumPy | savez method
Start your free 7-days trial now!
Numpy's savez(~)
method writes multiple Numpy arrays to a single file in .npz
format. Unlike the savez_compressed(~)
method, savez(~)
merely bundles up the arrays without compression.
Parameters
1. file
| file
or string
or pathlib.Path
The file to which the Numpy array will be written. The .npz
extension will be appended to the filename if the path does not already include it.
2. args
| Arguments
| optional
The arrays to save, with their names assigned as "arr_0"
, "arr_1"
and so on. These names will be needed later to access the arrays individually.
3. kwd
| Keyword arguments
| optional
The arrays to save, with their names specified by the keyword argument.
Return value
None.
Examples
Basic usage
To save multiple Numpy arrays:
filter_none
Copy
x = np.array([3,4,5])y = np.array([6,7,8])np.savez("my_data", x, y)
This saves our arrays in a single file called my_data.npz
, which exists in the same directory as our Python script.
To read this file later, use Numpy's load(~)
method like so:
filter_none
Copy
my_arrays = np.load("my_data.npz")print("x", my_arrays["arr_0"])print("y", my_arrays["arr_1"])
x [3 4 5]y [6 7 8]
Notice how the default name of the arrays are "arr_0"
and "arr_1"
.
You could also iterate over all the arrays like so:
filter_none
Copy
my_arrays = np.load("my_data.npz")for name in my_arrays: print("name:", name, "| array:", my_arrays[name])
name: arr_0 | array: [3 4 5]name: arr_1 | array: [6 7 8]
Naming arrays
Instead of the default names, you can assign custom names to the arrays using keyword arguments:
filter_none
Copy
x = np.array([3,4,5])y = np.array([6,7,8])np.savez("my_data", my_x=x, my_y=y)
Now, to fetch these arrays later:
filter_none
Copy
my_arrays = np.load("my_data.npz")print("x:", my_arrays["my_x"])print("y:", my_arrays["my_y"])
x: [3 4 5]y: [6 7 8]