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
     
  • 相关阅读:
    Java内存区域
    spring学习之Bean
    记一次日本公司的Java面试
    java中打印输出数组内容的三种方式
    Java创建子类时构造器执行顺序
    转发&重定向
    Java继承
    GXOI&GZOI
    LCT能干啥???
    后缀自动机的一些应用
  • 原文地址:https://www.cnblogs.com/baojun2014/p/9085533.html
Copyright © 2011-2022 走看看