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>