网络编程
位置:首页>> 网络编程>> Python编程>> 解决python中 f.write写入中文出错的问题

解决python中 f.write写入中文出错的问题

作者:清新阳光521  发布时间:2021-01-02 04:57:44 

标签: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()

来源:https://blog.csdn.net/baidu_21833433/article/details/70313783

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com