[Tutor] Writing to CSV string containing quote and comma

J Sutar jsutar at gmail.com
Mon Dec 9 22:52:34 CET 2013


# Re-sending from registered email address #.

Hi,

Posting for first time so hope I get the forum etiquette and rules right,
please let me know otherwise.

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


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

NumPlusWordQuoted=[]
for (i, j) in zip(Numbers,Words):
    NumPlusWordQuoted.append([str(i) + " " + chr(34) +  j + chr(34)])

print NumPlusWordQuoted

outputfile="c:/temp/test.csv"
ofile = open(outputfile, 'wb')
ofile.write(",".join(str(n) for n in Numbers)) # 1. Numbers works ok

ofile.write("\n" + ",".join(chr(34) + w + chr(34) for w in Words)) #
2. Words works ok

ofile.write("\n"+",".join(chr(34) + i[0] + chr(34) for i in
NumPlusWordQuoted)) #3. Number plus words in quotes fails

ofile.close()


A helping hand on this would be very much appreciated.

Thanks in advance.
Jignesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20131209/9d69d286/attachment.html>


More information about the Tutor mailing list