jklaus
jklaus

Reputation: 1394

Escape commas when writing string to CSV

I need to prepend a comma-containing string to a CSV file using Python. Some say enclosing the string in double quotes escapes the commas within. This does not work. How do I write this string without the commas being recognized as seperators?

string = "WORD;WORD 45,90;WORD 45,90;END;"
with open('doc.csv') as f:
    prepended = string + '\n' + f.read()
with open('doc.csv', 'w') as f:
    f.write(prepended)

Upvotes: 0

Views: 4318

Answers (1)

jspcal
jspcal

Reputation: 51914

So as you point out, you can typically quote the string as below. Is the system that reads these files not recognizing that syntax? If you use python's csv module it will handle the proper escaping:

with open('output.csv', 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(myIterable, quoting=csv.QUOTE_ALL)

The quoted strings would look like:

"string1","string 2, with, commas"

Note if you have a quote character within your string it will be written as "" (two quote chars in a row):

"string1","string 2, with, commas, and "" a quote"

Upvotes: 1

Related Questions