首页 > 代码库 > 【python】f.write()写入中文出错解决办法

【python】f.write()写入中文出错解决办法

一个出错的例子

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

 

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

 

解决方案一:

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

 

解决方案二:

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

 

【python】f.write()写入中文出错解决办法