亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我不想以二進制形式存儲它,所以我沒有將其設置為“wb”我該怎么辦?

我不想以二進制形式存儲它,所以我沒有將其設置為“wb”我該怎么辦?

UYOU 2023-12-09 17:12:07
import pickle    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 fichier :        record = pickle.Pickler(fichier)        record.dump(p)這是錯誤 write() 參數必須是 str,而不是 bytes
查看完整描述

3 回答

?
牛魔王的故事

TA貢獻1830條經驗 獲得超3個贊

將二進制轉換為 ascii 是很常見的,并且有幾種不同的常用協議可以完成此操作。此示例執行 Base64 編碼。十六進制編碼是另一種流行的選擇。任何使用此文件的人都需要知道其編碼。但它也需要知道它是一個 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())


查看完整回答
反對 回復 2023-12-09
?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

以防萬一 JSON 是您考慮的一個選項,下面是它的實現:


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)

結果:


This iz bob

ur name is bob and ur lvl12

ur name is bob and ur lvl12

bob is a Ice Cream Man

請注意,此實現的行為就像“dict”不存在一樣。構造函數采用單獨的起始值,并且可以隨意在對象上設置其他屬性,并且它們也可以保存和恢復。


序列化:


{"name": "bob", "level": 12, "occupation": "Ice Cream Man"}


查看完整回答
反對 回復 2023-12-09
?
30秒到達戰場

TA貢獻1828條經驗 獲得超6個贊

我一直試圖關注評論中的所有聊天,但對我來說沒有多大意義。您不想“以二進制形式存儲”,但 Pickle 是一種二進制格式,因此通過選擇 Pickle 作為序列化方法,就已經做出了該決定。因此,您的簡單答案就是您在主題行中所說的內容...使用“wb”而不是“w”,然后繼續(記住在讀回文件時使用“rb”):


p = player("bob",12)

with open("Player.pic", "wb") as fichierx:

    pickle.dump( p, fichierx )

如果您確實想使用基于文本的格式...人類可讀的格式,考慮到我在您的對象中看到的數據,這并不困難。只需將字段存儲在字典中,向對象添加方法,然后使用該load庫通過以 JSON 格式從磁盤讀取字典或將字典寫入磁盤來實現這些方法。storejson


據我所知,在腌制數據周圍添加一個“ascification”層有一個正當理由,那就是如果您希望能夠復制/粘貼它,就像您通常使用 SSH 密鑰、證書等那樣。也就是說,這并不會使您的數據更具可讀性......只是更容易移動,例如在電子郵件等中。如果這就是你想要的,盡管你沒有這么說,那么上面的所有內容都會回到桌面上,我承認。在這種情況下,請把我所有的胡言亂語理解為“告訴我們您的真正要求是什么”。


查看完整回答
反對 回復 2023-12-09
  • 3 回答
  • 0 關注
  • 164 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號