2016-06-10 88 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文檔中查看。

相關問題