您的位置:首页 > 编程语言 > Python开发

python 写文件编码错误 UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-10: ordinal n

2016-04-11 17:14 561 查看
python在写文件的时候经常遇到编码问题。下面直接上问题: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-10: ordinal not in range(128)我在写python文件的时候,汉字字符串编码是utf-8,写入txt文件时候报错。两种解决办法: 1 .
s="北京市第一中级人民法院"
s=s.decode("utf-8")
s=s.encode('GBK')
<strong>这时候的汉字字符串<em><span style="font-size:18px;">s</span></em>在写入txt时候就不会报错了。</strong>
<strong>2 .</strong>
<strong>由于写入到txt文件默认的编码为ANSI编码,可以自己先手动创建一个utf-8格式的txt文件,然后通过程序往这个txt文件写入utf-8编码的汉字字符串就可以了</strong>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: