I have a list that looks like this:
a = [['a string', [0, 0, 0], [22, 'bee sting']], ['see string',
[0, 2, 0], [22, 'd string']]]
and am having problems saving it and retrieving it.
I can save it ok using pickle:
with open('afile','w') as f:
pickle.dump(a,f)
but get the following error when I try to load it:
pickle.load('afile')
Traceback (most recent call last):
File "<pyshell#116>", line 1, in <module>
pickle.load('afile')
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 841, in __init__
self.readline = file.readline
AttributeError: 'str' object has no attribute 'readline'
I had thought that I could convert to a numpy array and use save
, savez
or savetxt
. However I get the following error:
>>> np.array([a])
Traceback (most recent call last):
File "<pyshell#122>", line 1, in <module>
np.array([a])
ValueError: cannot set an array element with a sequence
To add to @ Rapolas K's answer:
I found that I had problems with the file not closing so used this method:
Decided to make it as an answer. pickle.load method expects to get a file like object, but you are providing a string instead, and therefore an exception. So instead of:
you should do: