我尝试使用类似这样的代码来读取 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 编码仅扩展到 bytes
和 str
类型之间的转换。 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 thecodecs
module for the list of supported encodings.
例如,具有西欧/北美区域设置的 Windows 计算机通常会使用 8 位 Windows-1252 字符集(Python 将此编码称为 'cp1252'
)。
关于python - open()默认使用什么编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36303919/