python3默认使用什么编码,python 3.0 open()默认编码

I am trying to count the lines in a JSON file.

Click HERE to access my JSON file .

I tried to use the below code to count the lines.

input = open("json/world_bank.json")

i=0

for l in input:

i+=1

print(i)

But the above code is throwing a UniCodeDecode Error as shown below.

---------------------------------------------------------------------------

UnicodeDecodeError Traceback (most recent call last)

in ()

2

3 i=0

----> 4 for l in input:

5 i+=1

6

C:\Users\Subbi Reddy\AppData\Local\Continuum\Anaconda3\lib\encodings\cp1252.py in decode(self, input, final)

21 class IncrementalDecoder(codecs.IncrementalDecoder):

22 def decode(self, input, final=False):

---> 23 return codecs.charmap_decode(input,self.errors,decoding_table)[0]

24

25 class StreamWriter(Codec,codecs.StreamWriter):

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 3979: character maps to

Then i included encoding parameter in open function as shown below.

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

Then it started working and giving output as 500.

As far as i know python open should consider "utf8" as default encoding.

Where i am going wrong in here.

解决方案

The default UTF-8 encoding of Python 3 only extends to byte->str conversions. open() instead uses your environment to choose an appropriate encoding:

From the Python 3 docs for open():

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.

In your case, as you're on Windows with a Western Europe/North America, you will be given the 8bit Windows-1252 character set. Setting encoding to utf-8 overrides this.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值