[Tutor] Writing to CSV string containing quote and comma

Danny Yoo dyoo at hashcollision.org
Mon Dec 9 23:22:39 CET 2013


>
>  I'm trying to write to csv a string which contains double quotation
>> marks and a comma however I'm finding that the write reads the comma as a
>> delimiter. If try wrap the string around double quotes it clashes with the
>> raw quotes originally within the string text (which I'd like to/must
>> preserve). Replacing double quotes with single quotes is neither an option
>> as I may have text containing single quotes (as in the number four example
>> below).
>>
>> Python has a csv reader and writer module.  You should check it out.
>>
>>
Hi Jignesh,

I agree with Joel.  Don't try to build a csv writer from scratch unless you
have unusual requirements.  Whatever rules you're using to try to escape
quotes are most likely incomplete.


Here's an example:

################################################
>>> import io
>>> import csv
>>> b = io.BytesIO()
>>> writer = csv.writer(b)
>>> writer.writerow(["One", "Two", "Three, with comma", "Four 'with single
quote'", "Five"])
59L
>>> print(b.getvalue())
One,Two,"Three, with comma",Four 'with single quote',Five

## Let's try another example:
>>> writer.writerow(["This has a quote: \"", "and another one: '"])
43L
>>> print(b.getvalue())
One,Two,"Three, with comma",Four 'with single quote',Five
"This has a quote: """,and another one: '
################################################


As we can see from this example, the csv library knows how to deal with
commas, and also how to escape double quotes, all using the rules described
in RFC 4180.


You can find out more about the csv library here:

    http://docs.python.org/3/library/csv.html
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131209/9fa1c9f5/attachment.html>


More information about the Tutor mailing list