• 技术文章 >Python技术 >Python基础教程

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

    爱喝马黛茶的安东尼爱喝马黛茶的安东尼2019-09-21 09:11:04原创6030

    举个例子:

    1

    2

    3

    4

    5

    #coding:utf-8

    s = u'中文'

    f = open("test.txt","w")

    f.write(s)

    f.close()

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

    相关推荐:《Python基础教程

    解决方案一:

    1

    2

    3

    4

    5

    #coding:utf-8

    s = u'中文'

    f = open("test.txt","w")

    f.write(s.encode("utf-8"))

    f.close()

    解决方案二:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    #coding:utf-8

    import sys

      

    reload(sys)

    sys.setdefaultencoding('utf-8')

      

    s = u'中文'

    f = open("test.txt","w")

    f.write(s)

    f.close()

    专题推荐:python fwrite 中文乱码
    上一篇:python中的nan是什么意思 下一篇:python如何计算时间差

    相关文章推荐

    • python如何解决中文乱码问题• python urllib2中文乱码怎么解决

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网