引用自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,则在两种情况下读取的方式完全相同。
关于python - 为什么以两种不同的编码打开文件可以按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30726724/