csv module and None values

Peter Otten __peter__ at web.de
Tue Aug 25 10:49:07 EDT 2009


JKPeck wrote:

> On Aug 24, 10:43 pm, John Yeung <gallium.arsen... at gmail.com> wrote:
>> On Aug 24, 5:00 pm, Peter Otten <__pete... at web.de> wrote:
>>
>> > If I understand you correctly the csv.writer already does
>> > what you want:
>>
>> > >>> w.writerow([1,None,2])
>> > 1,,2
>>
>> > just sequential commas, but that is the special treatment.
>> > Without it the None value would be converted to a string
>> > and the line would look like this one:
>>
>> > 1,None,2
>>
>> No, I think he means he is getting
>>
>> >>> w.writerow([1,None,2])
>>
>> 1,"",2
>>
>> He evidently wants to quote "all" strings, but doesn't want None to be
>> considered a string.
>>
>> John
> 
> Exactly so.  The requirement of the receiving program, which is out of
> my control, is that all strings be quoted but a None in a numeric
> field result in the ,, output rather than "".  Excel quotes strings
> conditionally, which doesn't do what is needed in this case.  For
> QUOTE_NONNUMERIC to quote None values makes some sense, but it gets in
> the way of representing missing values in a numeric field.  It would
> be nice to have a choice here in the dialects.
> 
> I thought of replacing the None values with float(nan), since that has
> a numeric type, but unfortunately that results in writing the string
> (unquoted) nan for the value.  So the sentinel approach seems to be
> the best I can do.

How about:

>>> import csv, sys
>>> class N(int):
...     def __str__(self): return ""
...
>>> pseudo_none = N()
>>> w = csv.writer(sys.stdout, quoting=csv.QUOTE_NONNUMERIC)
>>> w.writerow([1, "foo", pseudo_none, "bar"])
1,"foo",,"bar"

Peter




More information about the Python-list mailing list