how to convert NPZ file to text file using python

Viewed 2210

Use this simple code to convert NPZ file to text file.

import numpy as np
import sys
data = np.load("file_name.npz")
print(data.files)
row = data.files
np.set_printoptions(threshold=np.inf)
print(data['arr_0'])
sys.stdout=open("test.txt","w")
for i in row:
    print("--------------------------")
    print(data[i])
sys.stdout.close()
1 Answers
#import packages we need
import numpy as np

Create example NPZ file

myarray = np.array([0,1,2,3])
np.savez('npzfile.npz',array0=myarray) # array0 will be the name with which you can retrieve myarray

Read it in

data = np.load('npzfile.npz')
data['array0'] # use array0 key to retrieve myarray

Result will be:

array([0, 1, 2, 3])

Which is a numpy array:

type(data['array0'])

Outputting numpy.ndarray.


If you don't know how NPZ was saved

You can do data.files. If you use the example NPZ above, this'll output ['array0']. This can help you knowing what are the names of the array when using data[name_of_array] (ie data[array0] above).

Related