python - 从文件读取时类型错误 :a bytes-like object is required, 而不是 'str'

标签 python string python-3.x byte file-handling

我正在尝试使用文件中的数据集在 ML 中实现我的项目

authors_file_handler = open(authors_file, "r")
authors = pickle.load(authors_file_handler)
authors_file_handler.close()

在此之后我在这一行中收到错误

authors = pickle.load(authors_file_handler)

TypeError: a bytes-like object is required, not 'str'

最佳答案

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

authors_file_handler = open(authors_file, "rb") # Note the added 'b'
authors = pickle.load(authors_file_handler)
authors_file_handler.close()

来自 pickle.load() docs :

The argument file must have two methods, a read() method that takes an integer argument, and a readline() method that requires no arguments. Both methods should return bytes. Thus file can be an on-disk file opened for binary reading, an io.BytesIO object, or any other custom object that meets this interface.

关于python - 从文件读取时类型错误 :a bytes-like object is required, 而不是 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52233295/

相关文章:

python - 对 python 中良好的递归性能感到惊讶

python - 使用多处理和 h5py

regex - 用 php preg_replace 只替换一次字符串

java - 用于捕获包含逗号和空格的数字和单词的复杂正则表达式

Python 3.2.2 从控制台读取

python - 执行返回值

python - Django 1.5 中缺少元类

python - 如何在Python(elementtree)中向musicXML树添加新元素?

python - 使用 readlines 从文件打印 - 新行加倍

javascript - 如何将 JavaScript Linkify 脚本与 _target ="blank"一起使用?