Python pickle/unpickle a list to/from a file

2019-01-19 10:36发布

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

2条回答
Deceive 欺骗
2楼-- · 2019-01-19 11:03

To add to @ Rapolas K's answer:

I found that I had problems with the file not closing so used this method:

with open('afile','rb') as f:
     pickle.load(f)
查看更多
趁早两清
3楼-- · 2019-01-19 11:18

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:

pickle.load('afile')

you should do:

pickle.load(open('afile', 'rb'))
查看更多
登录 后发表回答