Python pickle/unpickle 列表到/从文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18229082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python pickle/unpickle a list to/from a file
提问by atomh33ls
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:
我可以使用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:
我原以为我可以转换为一个 numpy 数组并使用save
,savez
或savetxt
. 但是我收到以下错误:
>>> 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
采纳答案by Rapolas K.
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 方法期望获得一个类似对象的文件,但您提供的是一个字符串,因此是一个例外。所以而不是:
pickle.load('afile')
you should do:
你应该做:
pickle.load(open('afile', 'rb'))
回答by atomh33ls
To add to @ Rapolas K's answer:
添加到@ Rapolas K 的回答中:
I found that I had problems with the file not closing so used this method:
我发现我的文件没有关闭有问题所以使用了这个方法:
with open('afile','rb') as f:
pickle.load(f)