csv module and None values

Peter Otten __peter__ at web.de
Mon Aug 24 23:00:44 CEST 2009


JKPeck 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 I understand you correctly the csv.writer already does what you want:

Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv, sys
>>> w = csv.writer(sys.stdout)
>>> w.writerow([1,None,2])
1,,2

just sequential commas, but that is the special treatment. Without it the 
the None value would be converted to a string and the line would look like 
this one:

>>> class LooksLikeNone:
...     def __str__(self): return "None"
...
>>> w.writerow([1,LooksLikeNone(),2])
1,None,2

Peter




More information about the Python-list mailing list