csv module and None values
gallium.arsenide at gmail.com
Tue Aug 25 06:34:57 CEST 2009
On Aug 24, 1:30 pm, JKPeck <jkp... at gmail.com> wrote:
> I'm trying to get the csv module (Python 2.6) to write data
> records like Excel. The excel dialect isn't doing it. The
> problem is in writing None values. I want them to result
> in just sequential commas - ,, but csv treats None specially,
> as the doc says,
> "To make it as easy as possible to interface with modules
> which implement the DB API, the value None is written as
> the empty string."
> I need strings to be quoted but not None values. Is there
> any way to get around this special None treatment?
If you need all nonempty strings to be quoted unconditionally, then
you are not writing CSV records the way Excel writes CSV records. The
csv module is surprisingly good at behaving like Excel, and by default
writes strings with quotes only when needed (that is, when the string
itself contains commas, quotes, or newlines).
If you truly want Excel-style CSVs, just let the csv module do its
thing, as pointed out by Peter Otten.
>From the sounds of it, you have specified QUOTE_NONNUMERIC or perhaps
QUOTE_ALL as the quoting property of the dialect you are using. If
so, and if this is really what you need except for *your* special None
treatment, then using a sentinel is in my opinion as good a way as any
to achieve that.
More information about the Python-list