CSV Module questions.
Dave Cole
djc at object-craft.com.au
Sun Sep 7 21:13:26 EDT 2003
> I'm trying to understand how to use the "csv" module. I assume this
> means "comma seperated values" in files. I quote from the docs...
>
>
> http://python.org/doc/current/lib/csv-fmt-params.html "When creating
> reader or writer objects, the programmer can specify a string or a
> subclass of the Dialect class as the dialect parameter"
>
> Ok, that's fine and dandy, but how do I specify it when I want to
> create a "writer" to write a simple dictionary to a file, and
> specify how it's to be written?
>
> Example (from the docs):
>
> # Just some stupid dictionary with key same as value.
> someiterable = {'john d': 'john d', 'fred': 'fred'}
>
> # make the writer.
> writer = csv.writer(file("some.csv", "w"))
> for row in someiterable:
> writer.writerow(row)
>
> Ok, so this made the file, but the file contents are thus...
>
> $ less some.csv
> j,o,h,n, ,d
> f,r,e,d
>
> which is NOT what I want. Obviously I have to probably make a
> "Dialect" or something like that. But how do I do that? Obviously,
> since Python severely lacks acceptable example code.... why didn't
> they just put in a few examples of how to do this? I certainly
> cannot figure this out.
>
> Here is what I want...
>
> "john d", "john d"
> "fred", "fred"
>
> How to I write to a file in this way? Is is possible?
When you write a "row" the writer expects the "row" to be a sequence.
Passing a string as the "row" the writer causes the string to be
handled as a row sequence thereby producing a row of single
characters.
Try this:
>>> import sys, csv
>>> w = csv.writer(sys.stdout)
>>> someiterable = {'john d': 'john d', 'fred': 'fred'}
>>> w.writerows(someiterable.iteritems())
john d,john d
fred,fred
- Dave
--
http://www.object-craft.com.au
More information about the Python-list
mailing list