编辑:
在2.7 / 3.2中有
a new writeheader() method.此外,John Machin的答案提供了一个更简单的写头行的方法。
使用writeheader()方法的简单示例现在可在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参数。
从the documentation:
The fieldnames parameter identifies
the order in which values in the
dictionary passed to the writerow()
method are written to the csvfile.
换句话说:Fieldnames参数是必需的,因为Python语句本质上是无序的。
下面是一个如何将头和数据写入文件的示例。
注意:with语句是在2.6中添加的。如果使用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在评论中提到的,您可以将标题缩写为单行文字,例如:
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)