如何使用csv.DictWriter编写标题行? [英] How to write header row with csv.DictWriter?
问题描述
假设我有一个csv.DictReader
对象,我想将其写为CSV文件.我该怎么办?
Assume I have a csv.DictReader
object and I want to write it out as a CSV file. How can I do this?
我知道我可以这样写行数据:
dr = csv.DictReader(open(f), delimiter='\t')
# process my dr object
# ...
# write out object
output = csv.DictWriter(open(f2, 'w'), delimiter='\t')
for item in dr:
output.writerow(item)
但是如何包含字段名?
推荐答案
在2.7/3.2中,有新的writeheader()
方法.同样,约翰·马钦(John Machin)的答案提供了一种更简单的写标题行的方法.
现在在2.7/3.2中提供了使用writeheader()
方法的简单示例:
In 2.7 / 3.2 there is a new writeheader()
method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader()
method now available in 2.7 / 3.2:
from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
dw.writeheader()
# continue on to write data
实例化DictWriter需要一个fieldnames参数.
来自文档:
Instantiating DictWriter requires a fieldnames argument.
From the documentation:
fieldnames参数标识 值在其中的顺序 传递给writerow()的字典 方法被写入到csvfile中.
The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.
以另一种方式:因为Python字典本质上是无序的,所以需要Fieldnames参数.
以下是如何将标头和数据写入文件的示例.
注意:with
语句是在2.6中添加的.如果使用2.5:from __future__ import with_statement
Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with
statement was added in 2.6. If using 2.5: from __future__ import with_statement
with open(infile,'rb') as fin:
dr = csv.DictReader(fin, delimiter='\t')
# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
headers = {}
for n in dw.fieldnames:
headers[n] = n
dw.writerow(headers)
for row in dr:
dw.writerow(row)
正如@FM在评论中提到的那样,您可以将标头编写压缩为单行代码,例如:
As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:
with open(outfile,'wb') as fou:
dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
for row in dr:
dw.writerow(row)
这篇关于如何使用csv.DictWriter编写标题行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!