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

289次阅读
没有评论

python

举个例子:

#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()
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-27发表,共计345字。
新手QQ群:570568346,欢迎进群讨论 Python51学习