我通过 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)
Run Code Online (Sandbox Code Playgroud)
UTF-8 和 ASCII 编解码器似乎都无法解码该文件。
然后我通过两个命令检查文件编码:
$ enca bugreport.txt
7bit ASCII characters
$ file -i bugreport.txt
bugreport.txt: text/plain; charset=us-ascii
Run Code Online (Sandbox Code Playgroud)
他们告诉我该文件是用 ascii 编码的,而我无法通过 ascii 编解码器打开它。
其他一些线索:
1.上面的python解释器是python 3.6.3。我尝试了 python 2.7.14 ,一切顺利。
2、如果添加参数errors='ignore'和encoding='ascii'打开文件,可以读取,但所有汉字都会丢失。
那么如何在 python 3 中打开这个特殊的文件呢?谁能帮我?
在 python 3 中,您可以使用开放上下文指定编码。
with open(file, encoding='utf-8') as f:
data = f.read()
Run Code Online (Sandbox Code Playgroud)