[Tutor] Writing to CSV string containing quote and comma

Steven D'Aprano steve at pearwood.info
Mon Dec 9 23:54:08 CET 2013


On Mon, Dec 09, 2013 at 09:52:34PM +0000, J Sutar wrote:

> 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).

Rather than manually writing strings to a file and hoping you get the 
rules right for a CSV file, you might find that it is easier to use 
Python's standard CSV module. It will handle all the escaping and 
quoting for you.

http://docs.python.org/2/library/csv.html

That is the best way to handle CSV in Python.

I haven't tried this, but I think this should handle your problem:


import csv

words = ["One", "Two", "Three, with comma", "Four 'with single quote'", "Five"]
numbers = [1, 2, 3, 4, 5]

with open("c:/temp/test.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerow(numbers)
    writer.writerow(words)
    writer.writerow(["%d %s" % (n, s) for n, s in zip(numbers, words)])



-- 
Steven


More information about the Tutor mailing list