zoukankan      html  css  js  c++  java
  • python2/python3中关于写入csv文件时会空一行以及中文编码问题的解决办法总结

        版权声明:本文为博主原创文章,转载请注明。

    运行环境:python2.7.13

              python3.6.0

           windows

       IDE:pycharm

    背景:做爬虫的时候需要写入csv格式,可是发现csv文件里的内容都是空一行显示一行,觉得特不爽,

         于是就网上查了下解决办法,多数情况下是说写入的时候以‘wb’的方式,发现在中文的情况下容易

              出乱码。后来便经过一番折腾,总结出python2和python3的情况下不同的解决方式。

    源码太长,为了方便说明,这里对写入内容给予简化。因为多数情况下在写入内容含中文的时候容易出错,

    所以举例子的时候将含有中文。

    (一) python2情况下

    1)在python2的情况下,首先要声明全局编码,我们这里用gbk而不是utf8.
         utf8也可以写入,只不过如果直接用表格打开csv文件,会看到乱码,如下图:

    2)另外使用open()函数的时候,要以‘wb’的方式打开,可以避免隔一行存储一行的情况。

    完整代码如下:

    #声明全局编码为gbk,如果用utf8编码,则直接用excel打开csv的时候,中文会显示乱码
    #
    coding:gbk import csv headers = ['ID','用户名','年龄','身高'] lines = [('1','文子','26','175'), ('2','祖文','27','185'), ('3','Bruce','28','195')] with open('wen.csv','wb') as f:#这里以‘wb’的方式打开,如果不用二进制b,则会隔一行存储一行 f_csv = csv.writer(f) f_csv.writerow(headers)#写入1行(列索引) f_csv.writerows(lines)#写入多行(数据)

     

    (二) python3情况下

    在python3的情况下比较好办,只需要在open()函数参数里写入newline=''即可,默认情况下newline=None,会换行写入,所以会空一行。

    完整代码如下:

    import csv
    
    headers = ['ID','用户名','年龄','身高']
    lines = [('1','文子','26','175'),
             ('2','祖文','27','185'),
             ('3','Bruce','28','195')]
    
    with open('wen.csv','w',newline='') as f:#以‘w’方式打开并写入属性newline='',则不会隔一行写入
        f_csv = csv.writer(f)
        f_csv.writerow(headers)#写入1行(列索引)
        f_csv.writerows(lines)#写入多行(数据)

    OK!完美显示:

    附:如果想知道为啥加上newline=''就不会空一行,感兴趣的同志们可以参考一下源码说明(On input是写入):

    newline controls how universal newlines works (it only applies to text
        mode). It can be None, '', '
    ', '
    ', and '
    '.  It works as
        follows:
        
        * On input, if newline is None, universal newlines mode is
          enabled. Lines in the input can end in '
    ', '
    ', or '
    ', and
          these are translated into '
    ' before being returned to the
          caller. If it is '', universal newline mode is enabled, but line
          endings are returned to the caller untranslated. If it has any of
          the other legal values, input lines are only terminated by the given
          string, and the line ending is returned to the caller untranslated.
        
        * On output, if newline is None, any '
    ' characters written are
          translated to the system default line separator, os.linesep. If
          newline is '' or '
    ', no translation takes place. If newline is any
          of the other legal values, any '
    ' characters written are translated
          to the given string.
    
  • 相关阅读:
    .NET Core+MySql+Nginx 容器化部署
    .NET Core容器化之多容器应用部署@Docker-Compose
    .NET Core容器化@Docker
    Hello Docker
    使用Bitbucket Pipeline进行.Net Core项目的自动构建、测试和部署
    一道面试题的思考
    ABP入门系列(21)——切换MySQL数据库
    爬取朋友圈,Get年度关键词
    一张图理清ASP.NET Core启动流程
    UnitOfWork知多少
  • 原文地址:https://www.cnblogs.com/lvzuwen/p/7358907.html
Copyright © 2011-2022 走看看