2016-06-10 36 views
0
if __name__ == "__main__": 
    h1 = Person(5) 
    print (h1) 

如上所示,我需要将类Person的对象h1另存为文本文件(.txt)。我想知道如何实现这种持久性并将其读回来?如何将类对象浸入文本文件并读取它?

一些用户建议使用泡菜,我想我可能需要更多的细节在这里。

+4

使用'pickle'模块。 – ppperry

+0

如果你真的需要一个文本文件(意思就像存储'h1 .__ repr __()'的输出),而不是“读回来”,理解为将文本评估为python声明以获取“h1”对象的副本这是可能的,但正如@ppperry所说,我很少有理由避免酸洗。只要注意(与文本存储的代码序列化一样),以仅消耗和评估你所托管或检查的内容。邪恶的事情可能发生在注射或篡改储存的物品后... – Dilettant

+0

@ppperry喜欢如何?你能详细解释一下吗? –

回答

1

这是一个可能的解决方案,让你开始。我改名的人实例名称和更改参数的名称;-)

#! /usr/bin/env python 
"""Note: Documentation clearly states, that classes can be pickled, 
but only iff they "are defined at the top level of a module".""" 
from __future__ import print_function 

import pickle 


class Person(object): 
    """Minimal class to showcase (un)pickle.""" 
    FULL_NAME_DEFAULT = 'N.N.' 

    def __init__(self, full_name=None): 
     """Detected initializer (show unpickling behaviour).""" 
     if full_name is not None: 
      self.full_name = full_name 
     else: 
      self.full_name = self.FULL_NAME_DEFAULT 
     print("Initializer called!") 
     self.say_hello() 

    def say_hello(self): 
     """A method to say a personalized hello.""" 
     print("Hello! My name is '%s'" % (self.full_name,)) 


def main(): 
    """Drive the dumps and loads of Person instances.""" 
    number_one = Person("Jane Awsome") 
    print(number_one) 
    print("# Serialize the person number_one ... with default protocol:") 
    serialized_person = pickle.dumps(number_one) 
    print("# Dump of the data representing the serialized_person:") 
    print(serialized_person) 
    print("# Now for something completely different ...") 
    reborn = pickle.loads(serialized_person) 
    print("# Back again a copy of number_one, no __init__ called ;-)") 
    reborn.say_hello() 

if __name__ == "__main__": 
    main() 

被我的机器上,并与Python运行时V2这导致:

Initializer called! 
Hello! My name is 'Jane Awsome' 
<__main__.Person object at 0x102e730d0> 
# Serialize the person number_one ... with default protocol: 
# Dump of the data representing the serialized_person: 
ccopy_reg 
_reconstructor 
p0 
(c__main__ 
Person 
p1 
c__builtin__ 
object 
p2 
Ntp3 
Rp4 
(dp5 
S'full_name' 
p6 
S'Jane Awsome' 
p7 
sb. 
# Now for something completely different ... 
# Back again a copy of number_one, no __init__ called ;-) 
Hello! My name is 'Jane Awsome' 

与Python V3伏法:

Initializer called! 
Hello! My name is 'Jane Awsome' 
<__main__.Person object at 0x1010c8780> 
# Serialize the person number_one ... with default protocol: 
# Dump of the data representing the serialized_person: 
b'\x80\x03c__main__\nPerson\nq\x00)\x81q\x01}q\x02X\t\x00\x00\x00full_nameq\x03X\x0b\x00\x00\x00Jane Awsomeq\x04sb.' 
# Now for something completely different ... 
# Back again a copy of number_one, no __init__ called ;-) 
Hello! My name is 'Jane Awsome' 

默认的协议改变了我的猜测:-)

请尽量抬头看您可能需要的详细信息用于扩展和适用您的使用案例,例如,在规范性文档中。 12.1. pickle — Python object serialization

...如果数据可能已经过调节,那么在取消打印时务必小心,因为您必须依赖您对此通道的信任。这是一个强大的。

所以就像使用JSON和其他(de)序列化模块一样,还有针对字符串,文件等进行优化的方法。您可以轻松地在文档中阅读它。这里我使用了dumps()和loads(),后缀s代表字符串。

对于序列化人员(这里是一个字符串变量)的内容输出到一个文件,在xou中回读可以很容易地在前述优秀的Python文档中查看。

相关问题