I want to combine combine fields from an input .csv file for output to a .csv file, and some contain commas. Here is my code, simplified
outfile = open('output.csv', 'w')
#these values are made up for this example; normally they would be read from
#a csv and passed to the following 'combine()' function
a = "John"
b = ",Jr."
def combine(a, b):
if a == "":
pass #don't write anything if the field is empty
else:
outfile.write(a)
if b =="":
pass
else:
outfile.write(b)
If b starts with a comma, how do I make the output “John, Jr.” ? I have tried using the csv.writer writerow() but it puts a comma delimiter between each character. I have tried defining an escapechar but it just outputs “John \” , “Jr.” Suggestions?
If you would like to know details about CSV, there is a spec: https://www.rfc-editor.org/rfc/rfc4180
In general it states the following
"Fields containing line breaks (CRLF), double quotes, and commas should be enclosed in double-quotes."
"If double-quotes are used to enclose fields, then a double-quote appearing inside a field must be escaped by preceding it with another double quote."
Implementations like Excel always put all field values into double quotes.
If you open a file for read or write you can specify the type of quoting directly
will always add quotes to the around the field value.
For all possible values look at the python documentation
http://docs.python.org/library/csv.html#module-csv