【问题标题】:How to get list of class instances from file using pickle如何使用pickle从文件中获取类实例列表
【发布时间】:2015-09-03 18:17:29
【问题描述】:

我有 2 个班级:小组和学生。我创建了不同组的列表,每个组都有包含学生列表的属性。然后我以这种方式使用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 在此处崩溃并给出下一个错误:

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

【问题讨论】:

  • 你为什么用with打开一次,然后又在with块内打开?
  • 还有Group指的是什么,你pickle了什么?
  • @PadraicCunningham 我删除了第二个开口,但没有帮助。
  • @PadraicCunningham Group 只是类的名称,然后我创建它的实例并将它们添加到列表中。
  • 如果在同一个文件中的类定义你正在做unpickling?

标签: python list python-2.7 pickle


【解决方案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 之前添加导入

【讨论】:

    【解决方案2】:

    您可以尝试使用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'>
    

    请注意,上面的答案实际上是存储列表子类的一个实例,即存储三个类实例。

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多