This question already has answers here:
Using pickle.dump - TypeError: must be str, not bytes

(2个答案)


2年前关闭。




在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转换为字节,但是仍然不能解决问题。有人可以告诉我怎么了吗?

最佳答案

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

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)

关于python - 泡菜: TypeError: a bytes-like object is required,而不是 'str' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39146039/

10-11 22:35
查看更多