[Tutor] Writing to CSV string containing quote and comma

J Sutar jsutar at gmail.com
Tue Dec 10 00:14:38 CET 2013


Thanks all. Yes csv module make it whole lot easier. I did try using it
before posting to list but couldn't get it working for some reason.

Steven, I updated the very last line of code as below, as I need to get the
word wrapped around quotes. Is that a good way of achieving that?

import csv
words = ["One", "Two", "Three, with comma", "Four 'with single quote'",
"Five"]
numbers = [1, 2, 3, 4, 5]
with open("c:/temp/test3.csv", "wb") as f:
    writer = csv.writer(f)
    writer.writerow(numbers)
    writer.writerow(words)
    writer.writerow([str(n) + " " + chr(34) + s + chr(34) for n, s in
zip(numbers, words)])


On 9 December 2013 22:54, Steven D'Aprano <steve at pearwood.info> wrote:

> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131209/93c70e58/attachment-0001.html>


More information about the Tutor mailing list