【发布时间】:2020-07-13 01:11:57
【问题描述】:
这是我尝试过的:
>>> with open("symbols.raw") as f:
... text=f.readlines()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python35\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 0x90 in position 1694: character maps to <undefined>
>>> with open("symbols.raw",encoding='utf-16') as f:
... text=f.readlines()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python35\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
File "C:\Python35\lib\encodings\utf_16.py", line 61, in _buffer_decode
codecs.utf_16_ex_decode(input, errors, 0, final)
UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 7500-7501: illegal encoding
>>> with open("symbols.raw",encoding='utf-8') as f:
... text=f.readlines()
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "C:\Python35\lib\codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 7: invalid start byte
当我尝试使用二进制模式时,它被加载了,但我无法理解如何在其中读取和编辑我自己的数据。
>>> with open("symbols.raw",'rb') as f:
... text=f.readlines()
...
这是文件:symbols.raw
请告诉我如何以人类解释的方式阅读它并在其中写入我自己的数据。 这是format of the symbols.raw file。
【问题讨论】:
-
为什么不将文件读取为二进制文件,然后将其解码为 utf-16?
-
@Avenger789 会不会和读取第二个错误中显示的 utf-16 编码的文件一样出现问题?
-
如您所见,我已经尝试过了。但不工作。其次,我说过我无法理解二进制文件。我已经写在问题中了。
-
你可以使用'rb'来阅读它,然后使用
structmod 来解释它,你可以在docs.python.org/3/library/struct.html#module-struct阅读文档 -
@Avenger789 尝试了你的想法:错误:
UnicodeError: UTF-16 stream does not start with BOM
标签: python python-3.x file