Python: file.read() 函数错误 - UnicodeDecodeErrors?

Python: file.read() function error - UnicodeDecodeErrors?

我如何从 python 中的原始 bin 文件中读取字节,因为 file.read() 函数以 UnicodeDecodeErrors 结尾?

具体来说,我正在阅读 a.bin 文件,但遇到了这个错误。

File "F:\Codes\Python\ML\Pybrain_test.py", line 27, in <module>
  string = img_set.read(784)
File "F:\Programs\Python\lib\encodings\cp1252.py", line 23, in decode
  return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x8d in position 1440: character maps to <undefined>

如果您仅使用 open(filename) 打开文件,它将被解释为文本,而不是字节。您应该将文件作为字节文件打开,如下所示:

f = open(filename, 'b')

然后f.read()就不会报那个错误了