【python】f.write()写入中文出错解决办法

一个出错的例子

#coding:utf-8
s = u'中文'
f = open("test.txt","w")
f.write(s)
f.close()

 

原因是编码方式错误,应该改为utf-8编码

 

解决方案一:

#coding:utf-8
s = u'中文'
f = open("test.txt","w")
f.write(s.encode("utf-8"))
f.close()

 

解决方案二:

#coding:utf-8
import sys

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

s = u'中文'
f = open("test.txt","w")
f.write(s)
f.close()

 

posted @ 2016-09-29 18:39  匡子语  阅读(19528)  评论(0编辑  收藏  举报