泡菜:TypeError:需要一个类似字节的对象,而不是"str" [英] Pickle: TypeError: a bytes-like object is required, not 'str'

查看:101
本文介绍了泡菜:TypeError:需要一个类似字节的对象,而不是"str"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I keep on getting this error when I run the following code in 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转换为字节,但是仍然不能解决问题.有人可以告诉我怎么了吗?

I tried converting the fname1 to bytes via the encode function, but It still isn't fixing the problem. Can someone tell me what's wrong?

推荐答案

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

You need to open the file in binary mode:

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

写作时:

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


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


As an aside, you should use with to handle opening/closing files:

阅读时:

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

写作时:

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

这篇关于泡菜:TypeError:需要一个类似字节的对象,而不是"str"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆