Issue with numpy.load

Viewed 44

First, I saved a NumPy array by the following command:

filename = 'D:\Data\\my_folder\\mydata.npy'
with open(filename, 'wb') as file:
     np.save(filename, numpy_array, allow_pickle=True, fix_imports=True)

The file is saved in the correct location.

Then, I tried to read it by

filename = 'D:\Data\\my_folder\\mydata.npy'
with open(filename, 'rb') as file:
     numpy_array = np.load(filename, allow_pickle=True, fix_imports=True)

However, it raised the following error:

UnpicklingError: Failed to interpret file 'D:\\Data\\my_folder\\mydata.npy' as a pickle

I was wondering if somebody could help me to fix this issue.

1 Answers

Per the .save and .load documentation, a simple filepath string will get the job done, and save the potential corruption. There is really no need to use a context manager to create the file object.

For example:

# Create and save.
a = np.arange(9).reshape(3,3)
np.save('3x3.npy', a, allow_pickle=True)

# Load array.
a_ = np.load('3x3.npy', allow_pickle=True)

Output a:

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

Output a_:

array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

Documentation excerpts:

.save

Parameters: file: file, str, or pathlib.Path
File or filename to which the data is saved. ...

.load

Parameters: file: file-like object, string, or pathlib.Path
The file to read. ...

Related