简体   繁体   English

错误消息:TypeError:需要一个类似字节的对象,而不是在Python中使用Pickle接收到的“ str”

[英]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.

相关问题 TypeError:需要一个类似字节的对象,而在用pickle加载时不是'str' - TypeError: a bytes-like object is required, not 'str' while loading with pickle Python错误:TypeError:需要一个类似字节的对象,而不是'str' - Python error: TypeError: a bytes-like object is required, not 'str' python错误TypeError:需要一个类似字节的对象,而不是'str' - python error TypeError: a bytes-like object is required,not 'str' Python SocketServer 错误:TypeError:需要类似字节的对象,而不是“str” - Python SocketServer Error : TypeError: a bytes-like object is required, not 'str' 类型错误:需要类似字节的 object,而不是使用子进程 python 的“str” - TypeError: a bytes-like object is required, not 'str' using Subprocess python TypeError:在Python 3中打开Python 2 Pickle文件时,需要一个类似字节的对象,而不是'str' - TypeError: a bytes-like object is required, not 'str' when opening Python 2 Pickle file in Python 3 需要一个类似字节的对象,在pickle python 3.6中不需要'str' - a bytes-like object is required, no 'str' with pickle python 3.6 使用套接字代码并将其更改为python 3.5.0并获取TypeError:需要一个类似字节的对象,而不是'str'错误 - Using socket code and changing it to python 3.5.0 and getting TypeError: a bytes-like object is required, not 'str' error Python 错误:“TypeError:需要类似字节的对象,而不是使用 UDP 协议的机器人控制器的‘str’” - Python Error: 'TypeError: a bytes-like object is required, not 'str'' for Robot Controller using UDP Protocol TypeError:需要一个类似字节的对象,而不是“str” - TypeError: a bytes-like object is required, not 'str'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM