python - 如何使用pickle从文件中获取类实例列表

标签 python list python-2.7 pickle

我有 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()

但是程序在这里崩溃并给出下一个错误:

enter image description here

我尝试以不同的类似方式从文件中读取此列表,但此错误始终相同,您能帮助我吗?

最佳答案

类定义必须在您 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/

相关文章:

python - 重置 time.clock()

java - JDialog 中的复选框列表

python - 使用 py2exe 为 python 代码构建可执行文件

旋转窗口不适合图像后的 Python 2.7.3 + OpenCV 2.4

python - 遍历列表返回负索引

python - Arduino与Python串口通信,使用十六进制值的问题

python - 使用主 Python 脚本中的子进程并行执行 2 个独立的 Python 脚本

python - 一些函数参数可以通过装饰器传递吗?

css - 在无序列表图像上应用灰度

Python:将列表与其索引进行比较并创建一个新列表