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

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


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

 

List1=['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
List2=['b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b']
List3=['c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c', 'c']

csvfile = open("D:/test.csv", 'w' ,encoding="UTF8",newline='') 
writer=csv.writer(csvfile, delimiter=",") 
writer.writerows(zip(List1,List2,List3))
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值