python2.7代码在python3.5环境下TypeError: a bytes-like object is required, not 'str'问题
这两天从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 <module>
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://www.geek-share.com/detail/2731314249.html给了很有用的信息,文章如下:
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 <module>
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')
程序不再报错,此方法简单,比其他百度出来的方法靠谱,屡试不爽
阅读更多- python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- python3.5 模拟UDP客户端发送数据报文,报错:TypeError: a bytes-like object is required, not 'str'
- python write()参数错误,导致报错TypeError: a bytes-like object is required, not 'str'
- Python 3.x Error:TypeError: a bytes-like object is required, not 'str'
- Python中3+版本运行2+版本程序出现TypeError: a bytes-like object is required, not 'str'之读取PDF中的图片
- python socket send 函数 报错:TypeError: a bytes-like object is required, not 'str'
- python中Base64编码和解码:TypeError: a bytes-like object is required, not 'str'
- python3中,socket使用send函数时出现的错误:TypeError: a bytes-like object is required, not 'str'
- Python 3.x: TypeError: a bytes-like object is required, not 'str'
- Python中“a bytes-like object is required, not 'str'”的问题
- TypeError: a bytes-like object is required, not 'str'
- Python学习中出现TpyeErrora bytes-like object is required, not 'str'
- TypeError: a bytes-like object is required, not 'str'
- Python 3.5 Socket TypeError: a bytes-like object is required, not 'str' 错误提示
- python问题:TypeError: a bytes-like object is required, not 'str'
- python 3.5: TypeError: a bytes-like object is required, not 'str'
- Python学习中出现TpyeErrora bytes-like object is required, not 'str'
- python2.7web代码用python3.6运行时,浏览器发送请求报错TypeError: Object of type 'bytes' is not JSON serializable的解决办法
- 【Python】TypeError: a bytes-like object is required, not 'str'解决