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

1

5 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]) 
1

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.

 import numpy as np data = np.load('imdb.npz', allow_pickle=True) lst = data.files for item in lst: print(item) print(data[item]) 
1

Use the load function:

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

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) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy