[Tutor] Modify a dictionary using csv.DictWriter

Alan Gauld alan.gauld at btinternet.com
Tue Jan 13 02:10:51 CET 2009


"Judith Flores" <juryef at yahoo.com> wrote

>   I have been struggling a while trying to figure out how to modify 
> a csv
> file using the csv.DictWriter class. Let's suppose I have the 
> following code:

I have never used DictWriter but...

> outfile=open('template.csv','w')     # This is a pre-existing file

Opening a file to write will create a new empty file. It will 
effectively delete
the pre existing file!

> 1. When I run the code above for the first time, the contents of the 
> pre-existing
> file disappear, if I run the script a second time, now I can see the 
> value of x.

Not sure why you see it on the second run but you are deleting the 
file
with the open call. You probably need to open one file for reading and
another for writing thenm at the end delete the first file (or rename 
it to .bak)
and overwrite with the written (modified) file.

> 2. The fieldnames don't appear in the csv file, only the values.
> 3. Is there a way to let the DictWriter know that the header of the 
> csv
> file corresponds to all the fieldnames? To avoid typing all the 
> names.

I can't help with that bit, sorry.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list