Reputation: 138
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?
Upvotes: 3
Views: 2175
Reputation: 18385
csv.writer
allows you to add a quoting
keyword which can be used to control how things are quoted.
You probably want something like csv.QUOTE_MINIMAL
.
>>> import csv
>>> with open('eggs.csv', 'wb') as outfile:
... writer = csv.writer(outfile, quoting=csv.QUOTE_MINIMAL)
... writer.writerow(['Spam'] * 5 + ['Baked Beans'])
... writer.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
Upvotes: 1
Reputation: 4756
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
mcvs = csv.writer(open('file.csv', 'wb'), quoting=csv.QUOTE_ALL)
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
Upvotes: 4
Reputation: 5494
And if you want to stick with pure Python:
resultStr = a+b
if ',' in resultStr: resultStr= '"' + resultStr + '"'
Upvotes: 0
Reputation: 298206
csv.writer writerow()
expects a list of values:
foo.writerow(['John', ',Jr.'])
Upvotes: 0