首页 > 解决方案 > 无法使用 Python 3 读取和编辑文件

问题描述

这是我尝试过的:

>>> 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()
...

这是文件:symbol.raw

请让我知道如何以人类解释的方式阅读它并在其中写入我自己的数据。这是symbols.raw 文件的格式

标签: pythonpython-3.xfile

解决方案


您可以使用encoding="ISO-8859-1"

with open("symbols.raw", encoding="ISO-8859-1") as f:
    text=f.readlines()

推荐阅读