' UTF-8'编解码器不能解码字节0x80

时间:2016-04-24 16:40:26

标签: python utf-8 caffe

我试图下载经过BVLC培训的模型而且我遇到了这个错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 110: invalid start byte

我认为这是因为以下功能(complete code

  # Closure-d function for checking SHA1.
  def model_checks_out(filename=model_filename, sha1=frontmatter['sha1']):
      with open(filename, 'r') as f:
          return hashlib.sha1(f.read()).hexdigest() == sha1

知道如何解决这个问题吗?

3 个答案:

答案 0 :(得分:15)

您正在打开非UTF-8编码的文件,而系统的默认编码设置为UTF-8。

由于您正在计算SHA1哈希值,因此您应该将数据读取为 binary hashlib函数要求您传入字节:

with open(filename, 'rb') as f:
    return hashlib.sha1(f.read()).hexdigest() == sha1

请注意在文件模式中添加b

请参阅open() documentation

  

mode 是一个可选字符串,用于指定打开文件的模式。它默认为'r',这意味着可以在文本模式下打开。 [...] 在文本模式下,如果未指定 encoding ,则使用的编码取决于平台:调用locale.getpreferredencoding(False)以获取当前的区域设置编码。 (对于读取和写入原始字节,请使用二进制模式并保留 encoding 未指定。)

来自hashlib module documentation

  

现在可以使用update()方法为此对象提供类似字节的对象(通常为字节)。

答案 1 :(得分:5)

您没有指定以二进制模式打开文件,因此f.read()正在尝试将文件读取为UTF-8编码的文本文件,这似乎不起作用。但是由于我们采用 bytes 的哈希值,而不是 strings 的哈希值,因此编码是什么并不重要,甚至文件是否都是文本:只是打开它,然后将其作为二进制文件读取。

>>> with open("test.h5.bz2","r") as f: print(hashlib.sha1(f.read()).hexdigest())
Traceback (most recent call last):
  File "<ipython-input-3-fdba09d5390b>", line 1, in <module>
    with open("test.h5.bz2","r") as f: print(hashlib.sha1(f.read()).hexdigest())
  File "/home/dsm/sys/pys/Python-3.5.1-bin/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 0xb8 in position 10: invalid start byte

>>> with open("test.h5.bz2","rb") as f: print(hashlib.sha1(f.read()).hexdigest())
21bd89480061c80f347e34594e71c6943ca11325

答案 2 :(得分:2)

由于文档和src代码中没有一个提示,我不知道为什么,但使用b char(我猜二进制)完全有效(tf-version:1.1.0):

image_data = tf.gfile.FastGFile(filename, 'rb').read()

For more information, check out: gfile

相关问题