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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM