Hello,

   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:

import csv
outfile=open('template.csv','w')     # This is a pre-existing file that 
contains 3 variables (3 columns). The variables will (or will not) have a value 
each.

x='new_value'      

writing=csv.DictWriter(outfile, 
fieldnames=['variable1','variable2','variable2'])

data={'variable1' : x}   # What I intent to do here is to overwrite whatever 
value exists for variable 1. There will always exist only one value per 
variable.

writing.writerow(data)

I have several questions about how DictWriter works, and I am sorry if my 
questions have a very obvious answer, which I am 'obviously' missing.


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.
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.


As usual, thank you very much for your help.


Judith


      
_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to