为了账号安全,请及时绑定邮箱和手机立即绑定

我不想以二进制形式存储它,所以我没有将其设置为“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条经验 获得超3个赞

以防万一 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 关注
  • 59 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信