品易云推流 关闭
文章详情页
文章 > Python基础教程 > python f.write中文乱码怎么解决

python f.write中文乱码怎么解决

头像

爱喝马黛茶的安东尼

2019-09-21 09:11:045546浏览 · 0收藏 · 0评论

举个例子:

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

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

相关推荐:《Python基础教程

解决方案一:

#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()
关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图