用csv.DictWriter写部分行吗? [英] Write a partial row with csv.DictWriter?

查看:138
本文介绍了用csv.DictWriter写部分行吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有一组输入的CSV文件.

I have a CSV file with a group of inputs.

示例:

A B C D

我想分析结果并为每行输出一个CSV文件,例如:

I want to analyze the results and output a CSV file for each row such as:

B C

DictReader使用适当的键"A","B","C","D"构建完整的字典.
DictWriter按预期设置字段.

The DictReader builds the full dictionary with the keys 'A' 'B' 'C' 'D' in it as it should.
The DictWriter sets up the fields as it is supposed to.

但是,当我尝试将数据发送到DictWriter时,出现错误消息:

However, when I attempt the send the data to the DictWriter, I get the error message:

ValueError: dict contains fields not in fieldnames: A D

我必须手动从字典中删除值条目,还是有一种简单的自动方法来进行设置?

Must I delete the value entries by hand from the dictionary or is there a simple automatic way to set this up?

我正在使用Python 2.6.6,并且无法更新到更高版本.

I am using Python 2.6.6 and am unable to update to a later version.

推荐答案

是的,有一种简单的方法.创建 csv.DictWriter 实例时使用时,只需将关键字参数extrasaction='ignore'传递给它-它的默认值是'raise',这是当您将其传递的字典中包含fieldnames参数.

Yes, there's a simple way to do it. When you create the csv.DictWriter instance being used, just pass it the keyword argument extrasaction='ignore'—the default value for it is 'raise', which is the cause of the ValueError exception you're getting when you pass it a dictionary with keys not specified in the fieldnames parameter.

顺便说一句,在提出SO问题之前阅读相关文档通常是值得的—并且通常可以立即提供答案.

BTW, reading the relevant documentation before asking SO questions is often a worthwhile endeavor—and can often provide answers without further delay.

这篇关于用csv.DictWriter写部分行吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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