在Python中使用Dictwriter输出时,为什么CSV文件在每个数据行之间都包含一个空行

2024-06-28 20:05:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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)

Tags: 文件csv数据inforoutput字典headers
3条回答

来自http://docs.python.org/library/csv.html#csv.writer

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

换句话说,当打开文件时,传递的是“wb”而不是“w”。
您还可以使用with语句在完成对文件的写入后关闭该文件。
测试示例如下:

from __future__ import with_statement # not necessary in newer versions
import csv
headers=['id', 'year', 'activity', 'lineitem', 'datum']
with open('file3.csv','wb') as fou: # note: 'wb' instead of 'w'
    output = csv.DictWriter(fou,delimiter=',',fieldnames=headers)
    output.writerow(dict((fn,fn) for fn in headers))
    output.writerows(rows)

更改此行中的“w”(写入):

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

到“wb”(写入二进制文件)为我修复了此问题:

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

Python v2.75: Open()

感谢@dandrejvv在上述原始帖子的评论中给出的解决方案。

默认情况下,csv模块中的类使用Windows样式的行结束符(\r\n),而不是Unix样式的(\n)。这可能是导致明显的双线中断的原因吗?

如果是,可以在DictWriter构造函数中重写它:

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

相关问题 更多 >