python:UnicodeEncodeError

时间:2023-03-09 13:37:58
python:UnicodeEncodeError

problem:

(<type 'exceptions.UnicodeEncodeError'>, UnicodeEncodeError('ascii', u'[taobao_cocobella_18808011629_\u9e45\u9ec4]\n', 30, 32, 'ordinal not in range(128)'), <traceback object at 0x1c4e3b0>)

solve:

  1. reload(sys)
  2. sys.setdefaultencoding('utf8')

在将字符串写入文件时,执行f.write(str),后台总是报错:UnicodeEncodeError: 'ascii' codec can't encode character u'\u8888' in position 0: ordinal not in range(168),即ascii码无法被转换成unicode码。在仔细推敲后发现,我所使用的python2.7,默认编码是ascii格式。可以使用如下语句查看python默认编码格式:

>>> import sys

>>> print(sys.getdefaultencoding())

当目标文件为utf-8,或你要读取的文件为utf-8时,系统就常识以ascii格式处理,所以就错了。

解决的办法就是:

方式1:   推荐使用

将str在代码里面编码成utf8,然后再处理

方式2:在python代码中进行改变,

import sys

reload(sys)

sys.setdefaultencoding('utf-8')

注意:使用此方式,有极大的可能导致print函数无法打印数据!

方式3:python安装目录下的lib\site-packages文件夹下新建一个sitecustomize.py,文件中的代码为:

import sys

sys.setdefaultencoding('utf-8')

值得欣慰的是,python3以后的版本默认编码格式是unicode格式,就无需如此麻烦了。