3 回答

TA貢獻(xiàn)1830條經(jīng)驗 獲得超3個贊
將二進(jìn)制轉(zhuǎn)換為 ascii 是很常見的,并且有幾種不同的常用協(xié)議可以完成此操作。此示例執(zhí)行 Base64 編碼。十六進(jìn)制編碼是另一種流行的選擇。任何使用此文件的人都需要知道其編碼。但它也需要知道它是一個 python pickle,所以不需要太多額外的工作。
import pickle
import binascii
class player :
def __init__(self, name , level ):
self.name = name
self.level = level
def itiz(self):
print("ur name is {} and ur lvl{}".format(self.name,self.level))
p = player("bob",12)
with open("Player.txt","w") as fichierx:
fichierx.write(binascii.b2a_base64(pickle.dumps(p)).decode('ascii'))
print(open("Player.txt").read())

TA貢獻(xiàn)1872條經(jīng)驗 獲得超4個贊
以防萬一 JSON 是您考慮的一個選項,下面是它的實現(xiàn):
import json
class Player(dict):
def __init__(self, name, level, **args):
super(Player, self).__init__()
# This magic line lets you access a Player's data as attributes of the object, but have
# them be stored in a dictionary (this object's alter ego). It is possible to do this with an
# explicit dict attribute for storage if you don't like subclassing 'dict' to do this.
self.__dict__ = self
# Normal initialization (but using attribute syntax!)
self.name = name
self.level = level
# Allow for on-the-fly attributes
for k,v in args.items():
self[k] = v
def itiz(self):
print("ur name is {} and ur lvl{}".format(self.name, self.level))
def dump(self, fpath):
with open(fpath, 'w') as f:
json.dump(self, f)
@staticmethod
def load(fpath):
with open(fpath) as f:
return Player(**json.load(f))
p = Player("bob", 12)
print("This iz " + p.name)
p.occupation = 'Ice Cream Man'
p.itiz()
p.dump('/tmp/bob.json')
p2 = Player.load('/tmp/bob.json')
p2.itiz()
print(p.name + "is a " + p.occupation)
結(jié)果:
This iz bob
ur name is bob and ur lvl12
ur name is bob and ur lvl12
bob is a Ice Cream Man
請注意,此實現(xiàn)的行為就像“dict”不存在一樣。構(gòu)造函數(shù)采用單獨(dú)的起始值,并且可以隨意在對象上設(shè)置其他屬性,并且它們也可以保存和恢復(fù)。
序列化:
{"name": "bob", "level": 12, "occupation": "Ice Cream Man"}

TA貢獻(xiàn)1828條經(jīng)驗 獲得超6個贊
我一直試圖關(guān)注評論中的所有聊天,但對我來說沒有多大意義。您不想“以二進(jìn)制形式存儲”,但 Pickle 是一種二進(jìn)制格式,因此通過選擇 Pickle 作為序列化方法,就已經(jīng)做出了該決定。因此,您的簡單答案就是您在主題行中所說的內(nèi)容...使用“wb”而不是“w”,然后繼續(xù)(記住在讀回文件時使用“rb”):
p = player("bob",12)
with open("Player.pic", "wb") as fichierx:
pickle.dump( p, fichierx )
如果您確實想使用基于文本的格式...人類可讀的格式,考慮到我在您的對象中看到的數(shù)據(jù),這并不困難。只需將字段存儲在字典中,向?qū)ο筇砑臃椒?,然后使用該load庫通過以 JSON 格式從磁盤讀取字典或?qū)⒆值鋵懭氪疟P來實現(xiàn)這些方法。storejson
據(jù)我所知,在腌制數(shù)據(jù)周圍添加一個“ascification”層有一個正當(dāng)理由,那就是如果您希望能夠復(fù)制/粘貼它,就像您通常使用 SSH 密鑰、證書等那樣。也就是說,這并不會使您的數(shù)據(jù)更具可讀性......只是更容易移動,例如在電子郵件等中。如果這就是你想要的,盡管你沒有這么說,那么上面的所有內(nèi)容都會回到桌面上,我承認(rèn)。在這種情況下,請把我所有的胡言亂語理解為“告訴我們您的真正要求是什么”。
添加回答
舉報