【问题标题】:Pickle: TypeError: a bytes-like object is required, not 'str' [duplicate]Pickle:TypeError:需要一个类似字节的对象,而不是'str' [重复]
【发布时间】:2017-01-01 22:20:07
【问题描述】:

当我在 python 3 中运行以下代码时,我不断收到此错误:

fname1 = "auth_cache_%s" % username
fname=fname1.encode(encoding='utf_8')
#fname=fname1.encode()
if os.path.isfile(fname,) and cached:
    response = pickle.load(open(fname))
else:
    response = self.heartbeat()
    f = open(fname,"w")
    pickle.dump(response, f)

这是我得到的错误:

File "C:\Users\Dorien Xia\Desktop\Pokemon-Go-Bot-Working-Hack-API-master\pgoapi\pgoapi.py", line 345, in login
    response = pickle.load(open(fname))
TypeError: a bytes-like object is required, not 'str'

我尝试通过编码函数将 fname1 转换为字节,但仍然无法解决问题。有人可以告诉我有什么问题吗?

【问题讨论】:

  • 这是否意味着我无法打开使用 Python 2.x 和 Python 3.x 腌制的文件?

标签: python python-3.x bots


【解决方案1】:

需要以二进制方式打开文件:

file = open(fname, 'rb')
response = pickle.load(file)
file.close()

写作时:

file = open(fname, 'wb')
pickle.dump(response, file)
file.close()

顺便说一句,您应该使用with 来处理打开/关闭文件:

阅读时:

with open(fname, 'rb') as file:
    response = pickle.load(file)

写作时:

with open(fname, 'wb') as file:
    pickle.dump(response, file)

【讨论】:

  • 我正在尝试加载 pickle 文件但遇到 _pickle.UnpicklingError: A load persistent id 指令遇到,但没有指定 persistent_load 函数。
【解决方案2】:

我一直回到这个堆栈溢出链接,所以我会在下次寻找它时发布真正的答案:

PickleDB 搞砸了,需要修复。

pickledb.py 的第 201 行

发件人:

simplejson.dump(self.db, open(self.loco, 'wb'))

到:

simplejson.dump(self.db, open(self.loco, 'wt'))

问题永远解决了。

【讨论】:

    【解决方案3】:

    您需要将“str”更改为“bytes”。试试这个:

    class StrToBytes:
        def __init__(self, fileobj):
            self.fileobj = fileobj
        def read(self, size):
            return self.fileobj.read(size).encode()
        def readline(self, size=-1):
            return self.fileobj.readline(size).encode()
    
    with open(fname, 'r') as f:
        obj = pickle.load(StrToBytes(f))
    

    【讨论】:

      【解决方案4】:

      在 Python 3 中,您需要专门调用“rb”或“wb”。

      with open('C:\Users\Dorien Xia\Desktop\Pokemon-Go-Bot-Working-Hack-API-master\pgoapi\pgoapi.py', 'rb') as file:
          data = pickle.load(file)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-05
        • 1970-01-01
        相关资源
        最近更新 更多