zoukankan      html  css  js  c++  java
  • python with open as f 写韩文中文乱码

    python3和python2的写法不一样具体如下:

    python3:

    with open(r'd:ssss.txt','w',encoding='utf-8') as f:

      f.write(u'中文')

    python2中open方法是没有encoding这个参数的,如果像python3一样的写法会报异常:TypeError: 'encoding' is an invalid keyword argument for this function

    python2中需要加上:

    import sys
    reload(sys)
    sys.setdefaultencoding('utf-8')
    with open(r'd:sss.txt','w') as f:
      f.write(unicode("xEFxBBxBF", "utf-8"))#函数将xEFxBBxBF写到文件开头,指示文件为UTF-8编码。
      f.write(u'中文')
    读取文件
    with open(r'd:aaa.txt','r') as ff:
      a= ff.read().encode('gbk')#编码为gbk输出 控制台
      print a
     
    或者还有一种写法:
     
    import io
    with io.open(path,'w',encoding='utf-8') as f:
      f.write(unicode("xEFxBBxBF", "utf-8"))#函数将xEFxBBxBF写到文件开头,指示文件为UTF-8编码。
      f.write(u'这是中文')
     
    with open(r'd:aaa.txt','r') as ff:
      a= unicode(ff.read(),'utf-8')#编码为UTF-8输出
      print a
     
  • 相关阅读:
    MUSIC分辨率与克拉美罗下界的关系
    EXCEL 基本函数
    新手如何正确的开始练车
    5.20考试整理
    树上倍增 x
    逆元 x
    BSGS ! x
    【テンプレート】LCA
    [HDOJ5783]Divide the Sequence(贪心)
    [HDOJ5791]Two(DP)
  • 原文地址:https://www.cnblogs.com/alex-13/p/9299825.html
Copyright © 2011-2022 走看看