Skip to main content
 首页 » 编程设计

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

2024年10月24日11Terrylee

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

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

我试图以不同的类似方式从文件中读取这个列表,但这个错误总是一样的,你能帮帮我吗?

请您参考如下方法:

类定义必须在你解开之前出现:

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' 这就是您在自己的代码中看到的。如果类定义在另一个文件中,请在尝试解开之前添加导入