为什么在使用Python中的Dictwriter输出时,CSV文件在每个数据行之间包含空行 [英] Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

查看:986
本文介绍了为什么在使用Python中的Dictwriter输出时,CSV文件在每个数据行之间包含空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用DictWriter将字典中的数据输出到csv文件。为什么CSV文件在每个数据行之间都有一个空行?这不是一个巨大的交易,但我的数据集是大的,并不适合一个csv文件,因为它有太多的行,因为双间距加倍的文件中的行数。



我写给字典的代码是:

  headers = ['id','year' ,'activity','lineitem','datum'] 
output = csv.DictWriter(open('file3.csv','w'),delimiter =',',fieldnames = headers)
output.writerow(dict((fn,fn)for fn in headers))
for row in rows:
output.writerow(row)
csv 模块中的类使用Windows-样式行终止符( \r\\\
)而不是Unix风格( \\\
)。



如果是这样,您可以在 DictWriter 构造函数中覆盖它:

  output = csv.DictWriter(open('file3.csv','w'),delimiter =',', lineterminator ='\\\
',fieldnames = headers)


I am using DictWriter to output data in a dictionary to a csv file. Why does the CSV file have a blank line in between each data line? It's not a huge deal, but my dataset is big and doesn't fit into one csv file because it has too many lines since the "double-spacing" doubles the number of lines in the file.

My code for writing to the dictionary is:

headers=['id', 'year', 'activity', 'lineitem', 'datum']
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)
output.writerow(dict((fn,fn) for fn in headers))
for row in rows:
    output.writerow(row)

解决方案

By default, the classes in the csv module use Windows-style line terminators (\r\n) rather than Unix-style (\n). Could this be what’s causing the apparent double line breaks?

If so, you can override it in the DictWriter constructor:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)

这篇关于为什么在使用Python中的Dictwriter输出时,CSV文件在每个数据行之间包含空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆