【问题标题】:TypeError:a bytes-like object is required, not 'str' when reading from a fileTypeError:从文件读取时需要一个类似字节的对象,而不是“str”
【发布时间】:2023-04-03 20:40:01
【问题描述】:

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

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

在这之后我在这行得到错误

作者 = pickle.load(authors_file_handler)

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

【问题讨论】:

  • 您在哪一行得到错误?请提供完整的追溯。
  • 试试:authors = pickle.load(bytes(authors_file_handler,encoding="utf-8"))

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


【解决方案1】:

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

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

来自pickle.load()docs

参数文件必须有两个方法,一个 read() 方法接受一个 整数参数和一个不需要参数的 readline() 方法。 两种方法都应该返回字节。因此文件可以是磁盘文件 为二进制读取打开、io.BytesIO 对象或任何其他自定义 符合该接口的对象。

【讨论】:

    猜你喜欢
    • 2016-01-05
    • 1970-01-01
    相关资源
    最近更新 更多