为什么以两种不同的编码打开文件会按预期工作?

Why does opening a file in two different encodings work as expected?

引用自here,

The default encoding is platform-dependent, so this code might work on your computer (if your default encoding is utf-8), but then it will fail when you distribute it to someone else (whose default encoding is different, like CP-1252).

上面引用中提到的代码:

fp = open('text.txt') # Assuming file exists
a_string = file.read()

我在当前目录下创建了一个名为text.txt(内容随机)的文件,其编码为"ANSI 1252"(使用notepad++检查)。我已经使用

检查了我的系统 (windows) 的默认编码
import locale
print(locale.getpreferredencoding())

给出输出

cp1252

读取文件的代码(我在引文下方提供)按预期工作。它甚至在我使用

时也有效
fp = open('text.txt', encoding='utf-8') # or `fp = open('text.txt', encoding='cp1252')`

以上代码如何适用于两种不同的编码?它不应该给出 UnicodeDecodeError 或类似的东西吗?

只有当输入包含编码映射之外的字符时,解码才会失败。如果您的文件是纯 ASCII 文件,那么在两种情况下读取的文件将完全相同。

here,映射是一样的。

据我了解,unicode 标准旨在向后兼容 ascii。