以下代码适用于 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/