[英]Error message: TypeError: a bytes-like object is required, not 'str' received using Pickle in Python
I'm trying to load a list back into the program from a text file using pickle: 我正在尝试使用pickle将列表从文本文件加载回程序中:
f = open("usernames.txt", "r")
usernames = pickle.load(f)
f.seek(0)
f.truncate(0)
f.close()
However when I run the code this error message appears: 但是,当我运行代码时,会出现此错误消息:
TypeError: a bytes-like object is required, not 'str'
How can I resolve this error? 如何解决此错误?
You need to open the file in binary mode so that reading from it produces byte strings, not Unicode strings. 您需要以二进制模式打开文件,以便从文件中读取会生成字节字符串,而不是Unicode字符串。
with open("usernames.txt", "rb") as f:
usernames = pickle.load(f)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.