【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()