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

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

一个出错的例子


#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

标签:python,f.write
0
投稿

猜你喜欢

  • prototype.js1.4版开发者手册

    2007-09-30 14:09:00
  • MySQL数据库的root口令恢复方法总结

    2009-08-19 09:03:00
  • keras model.fit 解决validation_spilt=num 的问题

    2023-11-07 19:11:52
  • 详解Python AdaBoost算法的实现

    2021-08-16 19:53:27
  • python 列表套json字典根据相同的key筛选数据

    2022-06-01 08:52:02
  • python flask之模板继承方式

    2022-05-26 03:38:24
  • python实现21点小游戏

    2023-11-21 08:58:27
  • WEB2.0网页制作标准教程(11)不用表格的菜单

    2008-02-19 19:36:00
  • ASP利用XMLHTTP实现表单提交以及cookies的发送的代码

    2011-04-15 10:37:00
  • python解析.pyd文件的详细代码

    2022-08-04 22:16:45
  • Python shelve模块实现解析

    2023-06-23 16:58:01
  • 使用eval()解析JSON格式字符串应注意的问题

    2008-04-16 15:46:00
  • CSS网页布局扩展小技巧

    2010-06-03 12:13:00
  • Python Tkinter 简单登录界面的实现

    2021-01-10 20:45:03
  • SQL学习笔记二 创建表、插入数据的语句

    2011-09-30 11:17:32
  • php session应用实例 登录验证

    2023-11-14 13:49:43
  • Python 标准库zipfile将文件夹加入压缩包的操作方法

    2021-09-17 14:06:10
  • python使用celery实现异步任务执行的例子

    2021-01-06 03:27:20
  • 数据库大战: MS SQL Server & IBM DB2

    2009-08-25 16:24:00
  • Pycharm取消py脚本中SQL识别的方法

    2023-10-30 16:23:13
  • asp之家 网络编程 m.aspxhome.com