简体   繁体   English

用 csv.DictWriter 写一个部分行?

[英]Write a partial row with csv.DictWriter?

I have a CSV file with a group of inputs.我有一个包含一组输入的 CSV 文件。

Example:例子:

A B C D

I want to analyze the results and output a CSV file for each row such as:我想分析结果并为每一行输出一个 CSV 文件,例如:

B C

The DictReader builds the full dictionary with the keys 'A' 'B' 'C' 'D' in it as it should. DictReader使用键 'A' 'B' 'C' 'D' 构建完整的字典。
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:但是,当我尝试将数据发送到DictWriter ,我收到错误消息:

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?我必须从字典中手动删除值条目还是有一种简单的自动方法来设置它?

I am using Python 2.6.6 and am unable to update to a later version.我使用的是 Python 2.6.6,无法更新到更高版本。

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.当您创建正在使用的csv.DictWriter实例时,只需将关键字参数extrasaction='ignore'传递给它 - 它的默认值是'raise' ,这是您在传递它时遇到的ValueError异常的原因带有未在fieldnames参数中指定的键的字典。

BTW, reading the relevant documentation before asking SO questions is often a worthwhile endeavor—and can often provide answers without further delay.顺便说一句,在提出 SO 问题之前阅读相关文档通常是值得的——并且通常可以毫不拖延地提供答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM