Python:无法读取ASCII编码的文件

2024-04-24 13:14:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我通过ADB在Android中生成了一个错误报告,并提取了这个大报告文件。但当我打开并阅读该文件时,它会打印:

>>> f = open('bugreport.txt')
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc0 in position 12788794: invalid start byte

>>> f = open('bugreport.txt', encoding='ascii')
>>> f.read()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode
    return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 5455694: ordinal not in range(128)

UTF-8和ASCII编解码器似乎都无法解码该文件。
然后我用两个命令检查文件编码:

^{pr2}$

他们告诉我文件是用ascii编码的,而我不能用ascii编解码器打开它。
其他一些线索:
1上面的python解释器是python3.6.3。我试用了Python2.7.14,结果很好。
2如果通过添加参数errors='ignore'和encoding='ascii'打开文件,则可以读取该文件,但会丢失所有的中文字符。在

那么,如何在python3中打开这个特殊的文件呢?有人能帮我吗?在


Tags: 文件inselftxtmostreadlineascii
2条回答

文件很可能被编码为拉丁语-1或utf-16(little-endian)。在

>>> bytes_ = [b'\xc0', b'\xef']
>>> for b in bytes_:
...     print(repr(b), b.decode('latin-1'))
... 
b'\xc0' À
b'\xef' ï
>>> bytes_ = [b'\xc0\x00', b'\xef\x00']
>>> for b in bytes_:
...     print(repr(b), b.decode('utf-16le'))
... 
b'\xc0\x00' À
b'\xef\x00' ï

在Python3中,您可以使用开放上下文指定编码。在

with open(file, encoding='utf-8') as f:
    data = f.read()

相关问题 更多 >