'How to open an .npz file

Someone sent me an .npz file. How can I open that file using Python, and read the data from it?



Solution 1:[1]

use this in python3:

from numpy import load

data = load('out.npz')
lst = data.files
for item in lst:
    print(item)
    print(data[item])

Solution 2:[2]

You want to use numpy.load() with a context manager:

with numpy.load('foo.npz') as data:
    a = data['a']

You should use a context manager here, as the documentation states:

the returned instance of NpzFile class must be closed to avoid leaking file descriptors.

and the context manager will handle that for you.

Solution 3:[3]

import numpy as np

data = np.load('imdb.npz', allow_pickle=True)
lst = data.files

for item in lst:
    print(item)
    print(data[item])

Solution 4:[4]

Use the load function:

import numpy as np
data = np.load('your_file.npz')

Solution 5:[5]

As indicated in the documentation of np.savez:

When opening the saved .npz file with load a NpzFile object is returned. This is a dictionary-like object that can be queried for its list of arrays (with the .files attribute), and for the arrays themselves.

You can easily treat it like a dictionary:

data = np.load('mat.npz')        # data contains x = [1,2,3,4,5]

for key in data.keys():
    print(key)                        # x
    print(data[key])                  # [1,2,3,4,5]

It is a dictionary-like object because you cannot assign directly to data which is NpzFile object, you will have this error TypeError: NpzFile' object does not support item assignment.

But you can convert it to a dictionary and use it completely as dictionary, and save it to .npz file like that:

data = dict(data)
data["y"] = np.arange(21)
np.savez("mat",**data) 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 N.S
Solution 2 syb0rg
Solution 3 KC PARK
Solution 4
Solution 5 Phoenix