TypeError:a bytes-like object is required, not 'str' when reading from a file

TypeError:a bytes-like object is required, not 'str' when reading from a file

我正在尝试使用文件中的数据集在 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.