Python设立默认语言编码

Python设置默认语言编码
当python中间处理非ASCII编码时,经常会出现如下错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0x?? in position 1: ordinal not in range(128)

0x??是超出128的数字,python在默认的情况下认为语言的编码是ascii编码,所以无法处理其他编码,需要设置python的

默认编码为所需要的编码。

一个解决的方案是在代码中添加:

    import sys  
      
    reload(sys)  
    sys.setdefaultencoding('utf8') #gb2312,gbk  
      
    print sys.getdefaultencoding() # 输出当前编码  


另一个方案是在 python的Lib\site-packages 文件夹下新建一个sitecustomize.py 文件(sitecustomize.py is a special script; Python will try to import it on startup, so any code in it will be run automatically.),输入:
import sys  
sys.setdefaultencoding('utf8')


这样就能够自动的设置编码了。

ps:
1. utf8的编码是:utf-8

2. 测试已经成功的方法:
>>> import sys
>>> sys.getdefaultencoding()