我有2个班:小组和学生。我创建了包含不同组的列表,每个组都包含包含学生列表的属性。然后我用这种方式用pickle将它保存到文件中:
encodedList = []
try:
with open('test') as file:
tfile = open( 'test', "r" )
encodedList = pickle.load( tfile )
except IOError:
tfile = open( 'test', "w" )
pickle.dump( encodedList, tfile )
tfile.close()
这三条线很好用。再次启动程序后,我想从列表中的文件中获取所有这些信息,我按照这样的许多教程来做:
.factory('someFac', function (CONFIG, $injector, $http) {
return $http.get('url').then(function (response) {
var temp = response.data.answer;
var answer = '';
if(temp == bar){
answer = barAnswer;
}
else if(temp == foo){
answer = fooAnswer;
}
return $injector.get(answer);
}
}
但是Programm崩溃了,给出了下一个错误:
我尝试以不同的方式从文件中读取此列表,但此错误始终相同,您能帮助我吗?
答案 0 :(得分:1)
类定义必须在你unpickle之前出现:
class foo(): # works
pass
encodedList = []
try:
with open('test') as file:
tfile = open( 'test', "r" )
encodedList = pickle.load( tfile )
except IOError:
tfile = open( 'test', "w" )
pickle.dump( encodedList, tfile )
tfile.close()
它是如何失败的:
encodedList = []
try:
with open('test') as file:
tfile = open( 'test', "r" )
encodedList = pickle.load( tfile )
except IOError:
tfile = open( 'test', "w" )
pickle.dump( encodedList, tfile )
tfile.close()
class foo(): # fails
pass
输出将是AttributeError: 'module' object has no attribute 'foo'
,这是您在自己的代码中看到的。如果类定义在另一个文件中,请在尝试unpickle之前添加导入
答案 1 :(得分:1)
您可以使用pickle
尝试不,而是使用更好的序列化工具,例如dill
。使用dill
,类定义与实例的pickle一起存储,因此如果您不知道要取消哪种类型的实例,则很容易。
>>> class Student(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
.. . return "Student(%s)" % self.name
...
>>> class Group(list):
... pass
...
>>> myclass = Group([Student('Ted'), Student('Fred'), Student('Jane')])
>>>
>>> import dill
>>> with open('myclass.pkl', 'w') as f:
... dill.dump(myclass, f)
...
>>>
在挑选实例列表后,退出并开始新会话......
Python 2.7.10 (default, Sep 2 2015, 17:36:25)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.40)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('myclass.pkl', 'r') as f:
... myclass = dill.load(f)
...
>>> myclass
[Student('Ted'), Student('Fred'), Student('Jane')]
>>> [student.name for student in myclass]
['Ted', 'Fred', 'Jane']
>>> type(myclass)
<class '__main__.Group'>
注意上面的答案实际上是存储一个列表子类的实例,即存储三个类实例。