这是我想了解的东西。我的印象是UTF-8向后兼容,因此即使它是ANSI文件,我也可以始终使用UTF-8解码文本文件。但这似乎并非如此:
In [1]: ansi_str = 'éµaØc'
In [2]: with open('test.txt', 'w', encoding='ansi') as f:
...: f.write(ansi_str)
...:
In [3]: with open('test.txt', 'r', encoding='utf-8') as f:
...: print(f.read())
...:
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-3-b0711b7b947e> in <module>
1 with open('test.txt', 'r', encoding='utf-8') as f:
----> 2 print(f.read())
3
c:\program files\python37\lib\codecs.py in decode(self, input, final)
320 # decode input (taking the buffer into account)
321 data = self.buffer + input
--> 322 (result, consumed) = self._buffer_decode(data, self.errors, final)
323 # keep undecoded input until the next call
324 self.buffer = data[consumed:]
UnicodeDecodeError: 'utf-8' codec can't decode bytes in position 0-1: invalid continuation byte
因此,如果我的代码期望使用UTF-8,并且可能遇到ANSI编码的文件,则需要处理UnicodeDecodeError。很好,但是如果有人能对我最初的误解有所了解,我将不胜感激。
谢谢!
答案 0 :(得分:1)
UTF-8向后兼容 ASCII 。不是ANSI。 “ ANSI”甚至没有describe any one particular encoding。而且您要测试的那些字符都在ASCII范围之外,因此,除非您实际使用UTF-8对其进行编码,否则无法将它们读取为UTF-8。