python csv模块dictwrite_从Python的csv模块使用DictWriter编写标头

1586010002-jmsa.png

Assume I have a csv.DictReader object and I want to write it out as a CSV file. How can I do this?

I know that I can write the rows like 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)

But how can I include the fieldnames?

解决方案

Edit:

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

Instantiating DictWriter requires a fieldnames argument.

From the documentation:

The fieldnames parameter identifies

the order in which values in the

dictionary passed to the writerow()

method are written to the csvfile.

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)

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值