您的位置:首页 > 编程语言 > Python开发

python2.7代码在python3.5环境下TypeError: a bytes-like object is required, not 'str'问题

2018-10-18 19:14 851 查看

这两天从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') 

程序不再报错,此方法简单,比其他百度出来的方法靠谱,屡试不爽

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐