我有 2 个类(class):小组和学生。我创建包含不同组的列表,每个组都有包含学生列表的属性。然后我以这种方式使用 pickle 将其保存在文件中:
tfile = open( 'test', "w" )
pickle.dump(encodedList, tfile)
tfile.close()
这 3 行代码效果很好。再次启动程序后,我想从列表中的文件中获取所有这些信息,我根据许多教程进行操作,如下所示:
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()
但是程序在这里崩溃并给出下一个错误:
我尝试以不同的类似方式从文件中读取此列表,但此错误始终相同,您能帮助我吗?
最佳答案
类定义必须在您 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 之前添加导入
关于python - 如何使用pickle从文件中获取类实例列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32382791/