Write a partial row with csv.DictWriter?

天涯浪子 提交于 2019-12-02 11:27:34

问题


I have a CSV file with a group of inputs.

Example:

A B C D

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

B C

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.

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?

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


回答1:


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.

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



来源:https://stackoverflow.com/questions/20977140/write-a-partial-row-with-csv-dictwriter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!