Issue
I'm using Python to output some data in a CSV file. It must absolutely be in a CSV file, I can't use anything else, that's what I'm ordered to do. The comma must be used as a separator, but sometimes the data contains a comma, so I put double quotes around the strings and it put them in one field. That's good so far, however what happens when the data also contains double quotes? There's no limit to what symbol can be contained in the data.
Solution
Don't reinvent the wheel, use the csv
module to write out your data:
import csv
with open(outputfilename, 'wb') as outfh:
writer = csv.writer(outfh)
writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
You can adjust quoting behaviour, but the default (Excel compatible) setting will handle quoting of commas and nested quotes for you. Columns containing quotes or commas are quoted, with any embedded quotes doubled.
Demo:
>>> from cStringIO import StringIO
>>> import csv
>>> out = StringIO()
>>> writer = csv.writer(out)
>>> writer.writerow(['Data with , commas and nested " quotes', 'works just fine'])
>>> out.getvalue()
'"Data with , commas and nested "" quotes",works just fine\r\n'
Answered By - Martijn Pieters Answer Checked By - Clifford M. (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.