Someone sent me an .npz file. How can I open that file using Python, and read the data from it?
15 Answers
use this in python3:
from numpy import load data = load('out.npz') lst = data.files for item in lst: print(item) print(data[item]) 1You 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
NpzFileclass must be closed to avoid leaking file descriptors.
and the context manager will handle that for you.
import numpy as np data = np.load('imdb.npz', allow_pickle=True) lst = data.files for item in lst: print(item) print(data[item]) 1Use the load function:
import numpy as np data = np.load('your_file.npz') 0As indicated in the documentation of np.savez:
When opening the saved .npz file with load
a NpzFile objectis returned. This is adictionary-like objectthat 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)