本文介绍了Python pickle /取消列表文件到/从文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
a = [[''string',[0,0, 0],[22,'being sting']],['see string',
[0,2,0],[22,'d string']]]
并且在保存和检索时遇到问题
我可以保存使用pickle:
with open('afile','w')as f:
pickle.dump(a ,f)
但是当我尝试加载时出现以下错误:
$文件< pyshell#116>,第1行,在< module>
pickle.load('afile')
文件C:\Python27\lib\pickle.py,第1378行,载入
返回Unpickler(file).load )
文件C:\Python27\lib\pickle.py,第841行,在__init__
self.readline = file.readline
AttributeError:'str'object has no属性'readline'
我以为我可以转换成一个numpy数组,并使用 save
, savez
或 savetxt
。但是我得到以下错误:
>>> np.array([a])
Traceback(最近一次调用的最后一个):
在< module>中,第1行的文件< pyshell#122>
np.array([a])
ValueError:无法设置数组元素的顺序
解决方案
决定将其作为答案。 pickle.load方法期望获得像对象一样的文件,但是你提供了一个字符串,因此是一个例外。所以,而不是:
pickle.load('afile')
$你应该这样做:
pickle.load(open(' afile','rb'))
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
orsavetxt
. 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
解决方案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'))
这篇关于Python pickle /取消列表文件到/从文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!