这两天从Github上下载2.7版本程序在3.5版本运行时TypeError: a bytes-like object is required, not 'str'这个错误花了我一天的时间来改找原因,下面将方法总结如下,一句话改动,屡试不爽:
报错如下:
Traceback (most recent call last):
File "cf_gan.py", line 226, in
main()
File "cf_gan.py", line 144, in main
param = pickle.load(open(workdir + "model_dns_ori.pkl"))
TypeError: a bytes-like object is required, not 'str'
博文:https://blog.csdn.net/Kerrwy/article/details/79457028给了很有用的信息,文章如下:
pickle.load()
当pickle.load(file)时,会直接报错:TypeError: file must have ‘read’ and ‘readline’ attributes;
当使用下面的这个代码运行时,
with open(file, 'rb') as f:
pickle.load(f)12
会报错UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0x8b in position 6: ordinal not in range(128)。
解决方法1:替换代码中的pickle.load(f)为pickle.load(f, encoding=’bytes’)即可,在python3中需要加入encoding=’bytes’,而python2中不需要。
解决方法2:
with open(file, 'rb') as f:
pickle.loads(f.read())
我采用方法1替换代码中的pickle.load(f)为pickle.load(f, encoding=’bytes’),最初用方法2改时,报错
Traceback (most recent call last):
File "cf_gan.py", line 240, in
main()
File "cf_gan.py", line 156, in main
param = pickle.load(data_file.read())
TypeError: file must have 'read' and 'readline' attributes
按照方法1将程序param = pickle.load(open(workdir + "model_dns_ori.pkl"))改为:
with open(workdir + "model_dns_ori.pkl",'rb') as data_file:
param = pickle.load(data_file,encoding='bytes')
程序不再报错,此方法简单,比其他百度出来的方法靠谱,屡试不爽