python - open()默认使用什么编码?

标签 python python-3.x utf-8 character-encoding

我尝试使用类似这样的代码来读取 JSON 文件(使用 UTF-8 编码):

input = open("json/world_bank.json")
i=0
for l in input:
    i+=1
print(i)

但是我遇到了UnicodeDecodeError。但是,一旦我尝试显式指定编码,它就开始工作:

input = open("json/world_bank.json",encoding="utf8")

我认为open函数会使用“utf8”作为默认编码?为什么需要指定?

最佳答案

Python 3 的默认 UTF-8 编码仅扩展到 bytesstr 类型之间的转换。 open() 改为 chooses an appropriate default encoding based on the environment :

encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

例如,具有西欧/北美区域设置的 Windows 计算机通常会使用 8 位 Windows-1252 字符集(Python 将此编码称为 'cp1252')。

关于python - open()默认使用什么编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303919/

相关文章:

Python3 刮刀。直到最后才解析 xpath

utf-8 - 检查某个字母是否属于俄语字母表

python 2.7 : wmi module: Creating an interactive process on a remote system

python - 如何编辑pdf文件并替换其数据?

python - django-registration 应用程序和 Django 1.5 自定义用户模型

python - ValueError : If using all scalar values, 你必须传递一个索引

Python错误: Setting an array element with a sequence

python - 在 Python 中使用 lambda 的 tkinter 按钮命令

utf-8 - UTF8 和 UTF-8 之间的正确术语

c - UTF8控制台输出: MultiByteToWideChar vs mbsrtowcs