Search code examples
numpynumpy-ndarraypython-unicodereadlines

Numpy.save list of different sized arrays gives: TypeError: '_io.TextIOWrapper' object is not subscriptable


Here is my code:

import numpy as np

mylist = [np.arange(0,1, 0.5), np.arange(0,2,0.5)]

np.save('mylist', mylist)

with open('mylist.npy') as last:
    print(lst[0])

I'm getting the error

    TypeError                                 Traceback (most recent call last)
<ipython-input-7-2461c8fce207> in <module>
      6 
      7 with open('mylist.npy') as lst:
--->  8     print(lst[0])

TypeError: '_io.TextIOWrapper' object is not subscriptable

I've tried modifying the code according to other posts that are similar, such as including lst = lst.read() or lst = lst.readlines(), but that gives me a Unicode error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x93 in position 0: invalid start byte

Does anyone have any suggestions? Thanks!


Solution

  • The solution, as commented by hpaulj, is to use np.load rather than read or readlines.

    import numpy as np
    
    mylist = [np.arange(0,1, 0.5), np.arange(0,2,0.5)]
    
    np.save('mylist', mylist)
    
    with open('mylist.npy') as last:
        lst = np.load(lst, allow_pickle = True)
        print(lst[0])