python - 代码适用于 Python 2,但不适用于 Python3 TypeError : a bytes-like object is required, 而不是 'str'

标签 python python-3.x pickle python-2.x

以下代码适用于 Python 2.7:

import os
import pickle

modelpath = "models/"

gmm_files = [os.path.join(modelpath,fname) for fname in 
          os.listdir(modelpath) if fname.endswith('.gmm')]

models    = [pickle.load(open(fname,'r')) for fname in gmm_files]

但是,当我在 Python3 中运行代码时,我从最后一行收到以下错误:

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

为了得到更好的想法,我尝试打印 print([type(open(fname,'r')) for fname in gmm_files])在两个版本中,发现在 python 2 中,类型是 <type 'file'>在 Python 3 中,类型为 <class '_io.TextIOWrapper'> .

我已经检查了这些 stackoverflow 问题,但它们都没有对此提供有用的答案:

python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

更新

这里的一堆答案据说要改变open(fname, 'r')open(fname, 'rb')但这只会导致另一个错误: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc0 in position 0: ordinal not in range(128)

最佳答案

作为documentation对于 pickle.load 方法说(强调我的):

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.

open(stuff, 'r') 将打开文件以读取文本,而不是原始字节。因此,open(stuff, 'r').read 将返回 str,而不是 bytes。要解决此问题,请以二进制模式打开文件:open(stuff, 'rb')

关于python - 代码适用于 Python 2,但不适用于 Python3 TypeError : a bytes-like object is required, 而不是 'str',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50763584/

相关文章:

python - 我怎么知道 python 3 使用的是 cPickle 还是 Pickle?

Python pickle 使用 getattr 进行循环递归?

python - 对象与引用

python - 如何从数据框中删除任何行中包含特定值的列

python - 正则表达式从文本中删除 URL

python - 如何将 Pandas 数据拆分为对象中的 2 位小数

python - 试图了解 OAuth2 refresh_token 流程 - 不断获得 invalid_grant

linux - 读取带有 unicode 字符的文本文件 - Python3

python-3.x - 从日期时间索引输出唯一年份集

Python:将可选参数设置为默认值