设为首页 加入收藏

TOP

python2/python3中关于写入csv文件时会空一行以及中文编码问题的解决办法总结
2017-09-30 16:57:33 】 浏览:1499
Tags: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.

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇数据分析实战 下一篇【原创】Superset在windows下的安..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目