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, '', '\n', '\r', and '\r\n'.  It works as
    follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' 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 '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.

 

转载于:https://www.cnblogs.com/lvzuwen/p/7358907.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值