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
     
  • 相关阅读:
    字符数组与指针
    终于在博客园安家了
    关于SET NOCOUNT
    如何判断请求是否发送成功以及获取请求中的数据
    mysql进阶 withas 性能调优
    Linux mkdir
    Linux umask and chmod
    C linux Debug
    Linux sed
    Linux ulimit
  • 原文地址:https://www.cnblogs.com/alex-13/p/9299825.html
Copyright © 2011-2022 走看看