[Tutor] Modify a dictionary using csv.DictWriter

John Fouhy john at fouhy.net
Tue Jan 13 02:23:37 CET 2009


2009/1/13 Judith Flores <juryef at yahoo.com>:
> Hello,

Hi Judith,

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

This is a consequence of this line:

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

In python (and most programming languages), if you open a file for
writing (mode 'w'), you automatically get a new, empty file.  Any
existing file with the same name is lost.

If you want to add records to the end of the file, you can open in
append mode ('a').  See the python library documentation for "Built-in
Functions" for more.
(the docs also mention mode 'a+', which is for "updating".  I confess
that I do not know the difference between 'a' and 'a+' (or 'w' and
'w+' for that matter))

If you want to modify rows in a csv file, your only option is:
 1. Read the csv file into a python data structure.
 2. Make the appropriate changes.
 3. Write all the data out to a new csv file.

CSV files aren't really intended as mutable data stores.  If this is
what you want, perhaps the shelve module would work better for you
(it's like a dict, but on disk), or even a relational database such as
sqlite3 (included with python 2.5 and up).

> 2. The fieldnames don't appear in the csv file, only the values.

I don't think the csv module will write a header row.  However, it is
easy enough to do yourself: just:

fieldnames = ['variable1', 'variable2', 'variable3']
outfile.write(','.join(fieldnames) + '\n')

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

If you read in the csv file using DictReader, you should have access
to the field names as keys of the dictionaries (although possibly not
in the same order).  Alternatively, just type them out once and give
them a name:

fieldnames = ['variable1', 'variable2', 'variable3']

After all, your program should probably know what your data looks like :-)

HTH.

-- 
John.


More information about the Tutor mailing list