python f.write中文乱码的解决方法

这篇文章主要介绍了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()

感谢你能够认真阅读完这篇文章,希望小编分享python f.write中文乱码的解决方法内容对大家有帮助,同时也希望大家多多支持亿速云,关注行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!