CSV Module questions.

Emile van Sebille emile at fenx.com
Sun Sep 7 18:56:39 EDT 2003


John D. asks:

[snip question and most of questionable example]
> someiterable = {'john d': 'john d', 'fred': 'fred'}
> # make the writer.
> writer = csv.writer(file("some.csv", "w"))
> for row in someiterable:
>     writer.writerow(row)
[snip]
> Here is what I want...
>
> "john d", "john d"
> "fred", "fred"
>
> How to I write to a file in this way?    Is is possible?
>

I expect you'll get further passing a list, as passing a dictionary also
requires setting up field names.  So instead try one of:

import csv
someiterable = [['john d', 'john d'], ['fred', 'fred']]
writer = csv.writer(file("somelist.csv", "wb"))
writer.writerows(someiterable)

#--- or ---

someiterable = [{'name': 'john d', 'addr':"123 Main"},
                {'name': 'fred',   'addr':"456 Spruce"}]
writer = csv.DictWriter(file("somedict.csv", "wb"), fieldnames =['name',
'addr'])
writer.writerows(someiterable)

HTH

Emile van Sebille
emile at fenx.com









More information about the Python-list mailing list