从Python的csv模块使用DictWriter编写标头 [英] Writing header with DictWriter from Python's csv module

查看:2846
本文介绍了从Python的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)

但是如何包含fieldnames?

But how can I include the fieldnames?

推荐答案

编辑:

在2.7 / 3.2中有新的 writeheader()方法。此外,John Machin的回答提供了一种更简单的写头行的方法。

使用 writeheader()方法的简单示例现在可用于2.7 / 3.2 :


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





$ b b

实例化DictWriter需要一个fieldnames参数。

文档


fieldnames参数标识

字典中的值传递的顺序

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

另一种方式:Fieldnames参数是必需的,因为Python

下面是如何将头和数据写入文件的示例。

注意:与 c $ c>语句在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)

这篇关于从Python的csv模块使用DictWriter编写标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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