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

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

  • Python 2
  • Python 3

使用writerows函数,可一次性将元组/列表的内容导出到文本文件,但会存在一行数据间隔一行空白行的现象,类似下图:
python3 使用writerows写入csv时有多余空行的处理办法_第1张图片.
解决方法:
在打开文件时,手工指定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文件如下图,达到预期效果:
python3 使用writerows写入csv时有多余空行的处理办法_第2张图片

参考资料如下(摘自: 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)

你可能感兴趣的:(python)