错误UnicodeDecodeError:'utf-8'编解码器无法解码位置0的字节0xff:无效的起始字节

新手上路,请多包涵

https://github.com/affinelayer/pix2pix-tensorflow/tree/master/tools

在上述站点上编译“process.py”时出错。

  python tools/process.py --input_dir data --            operation resize --outp
ut_dir data2/resize
data/0.jpg -> data2/resize/0.png

回溯(最近一次通话最后):

 File "tools/process.py", line 235, in <module>
  main()
File "tools/process.py", line 167, in main
  src = load(src_path)
File "tools/process.py", line 113, in load
  contents = open(path).read()
      File"/home/user/anaconda3/envs/tensorflow_2/lib/python3.5/codecs.py", line 321, in decode
  (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode     byte 0xff in position 0: invalid start byte

错误的原因是什么? Python 的版本是 3.5.2。

原文由 pie 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 853
2 个回答

Python 尝试将字节数组(a bytes 它假定为 utf-8 编码的字符串)转换为 unicode 字符串( str )。这个过程当然是按照utf-8规则进行解码。当它尝试这样做时,它遇到了一个 utf-8 编码字符串中不允许的字节序列(即位置 0 处的这个 0xff)。

由于您没有提供任何我们可以查看的代码,我们只能猜测其余部分。

从堆栈跟踪中,我们可以假设触发操作是从文件中读取( contents = open(path).read() )。我建议以这样的方式重新编码:

 with open(path, 'rb') as f:
  contents = f.read()

That b in the mode specifier in the open() states that the file shall be treated as binary, so contents will remain a bytes .这种方式不会发生解码尝试。

原文由 Alfe 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用此解决方案,它将去除(忽略)字符并返回没有它们的字符串。仅当您需要剥离它们而不是转换它们时才使用它。

 with open(path, encoding="utf8", errors='ignore') as f:

使用 errors='ignore' 你只会丢失一些字符。但是如果你不关心它们,因为它们似乎是额外的字符,源于连接到我的套接字服务器的客户端的错误格式和编程。那么它是一个简单的直接解决方案。 参考

原文由 Nitish Kumar Pal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题