How can i quote escape characters in csv writer in python

I am writing the csv file like this

for a in products:
    mylist =[]
    for h in headers['product']:
        mylist.append(a.get(h))
        writer.writerow(mylist)

My my few fields are text fields can conatins any characters like , " ' \n or anything else. what is the safest way to write that in csv file. also file will also have integers and floats

Best answer

You should use QUOTE_ALL quoting option:

import StringIO
import csv

row = ["AAA \n BBB ,222 \n CCC;DDD \" EEE ' FFF 111"]

output = StringIO.StringIO()
wr = csv.writer(output, quoting=csv.QUOTE_ALL)
wr.writerow( row )

# Test:
contents = output.getvalue()
parsedRow = list(csv.reader([contents]))[0]

if parsedRow == row: print "BINGO!"