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

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

问题描述

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

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.

我写字典的代码是:

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 样式的行终止符 ( ) 而不是 Unix 风格的 ( ).这可能是导致明显双换行符的原因吗?

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

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

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

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

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

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