UnicodeEncodeError: 'ascii' codec can't encode character...的解决方法

Posted zhouxinfei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UnicodeEncodeError: 'ascii' codec can't encode character...的解决方法相关的知识,希望对你有一定的参考价值。

在python2.7下,因为想从数据库中读出来分类名进行写入到文件,提示

Traceback (most recent call last):
  File "test.py", line 28, in <module>
    fp.write("%d:%s\r\n"%(sClassid,sClassName))
UnicodeEncodeError: ascii codec cant encode character u\uff08 in position 12: ordinal not in range(128)

 

不用fp.write,用print打印却正常,这到底是怎么回来呢?

#! /usr/bin/python
# -*- coding: utf-8 -*-
import sys
print sys.getdefaultencoding();

 

运行上面的程序提示

ascii

原来如此,在程序的头部加上

import sys

reload(sys)
sys.setdefaultencoding(utf-8)

 

再次运行,错误消息。

总结一下,python2.7是基于ascii去处理字符流,当字符流不属于ascii范围内,就会抛出异常(ordinal not in range(128)。

以上是关于UnicodeEncodeError: 'ascii' codec can't encode character...的解决方法的主要内容,如果未能解决你的问题,请参考以下文章

UnicodeEncodeError: 'ascii' codec can't encode character u'u5929' in position 2(

UnicodeEncodeError: 'ascii' codec can't encode characters

UnicodeEncodeError: 'ascii' codec can't encode characters in

UnicodeEncodeError: 'gbk' codec can't encode character 'xbb' in position

UnicodeEncodeError: 'ascii' codec can't encode character...的解决方法

UnicodeEncodeError: 'gbk' codec can't encode character 'u25aa' in position 15: (