当前位置:   article > 正文

python3 使用writerows写入csv时有多余空行的处理办法

python3 使用writerows写入csv时有多余空行的处理办法

python3 使用writerows写入csv时有多余空行的处理办法


使用writerows函数,可一次性将元组/列表的内容导出到文本文件,但会存在一行数据间隔一行空白行的现象,类似下图:
在这里插入图片描述.
解决方法:
在打开文件时,手工指定newline参数为""即可避免空行。
修改后的代码如下:

 

  1. List1=['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
  2. List2=['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
  3. List3=['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c']
  4. csvfile = open("D:/test.csv", 'w' ,encoding="UTF8",newline='')
  5. writer=csv.writer(csvfile, delimiter=",")
  6. writer.writerows(zip(List1,List2,List3))
  7. csvfile.close()

执行后的csv文件如下图,达到预期效果:
在这里插入图片描述

参考资料如下(摘自: https://stackoverflow.com/questions/3348460/csv-file-written-with-python-has-blank-lines-between-each-row):
In Python 2, open outfile with mode ‘wb’ instead of ‘w’. The csv.writer writes \r\n into the file directly. If you don’t open the file in binary mode, it will write \r\r\n because on Windows text mode will translate each \n into \r\n.

In Python 3 the required syntax changed, so open outfile with the additional parameter newline=’’ instead.

Examples:

Python 2

with open(’/pythonwork/thefile_subset11.csv’, ‘wb’) as outfile:
writer = csv.writer(outfile)

Python 3

with open(’/pythonwork/thefile_subset11.csv’, ‘w’, newline=’’) as outfile:
writer = csv.writer(outfile)

转自:https://blog.csdn.net/warlocker1982/article/details/83058526

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/43955?site
推荐阅读
相关标签
  

闽ICP备14008679号