Skip to main content
 首页 » 编程设计

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

2024年09月07日8hnrainll

我通过 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编解码器都不能解码文件。
然后我通过两个命令检查了文件编码:

$ enca bugreport.txt 
7bit ASCII characters 
$ file -i bugreport.txt 
bugreport.txt: text/plain; charset=us-ascii 

他们告诉我文件是用 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()