How can I quote escape characters in csv writer in python

I am writing a csv file like this

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

My my fields are text fields that can contain any type characters , " ' \nor something else. what is the safest way to write this in a csv file. also the file will also have integers and float

+5
source share
2 answers

You should use the QUOTE_ALL 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!"
+6
source

using csv.QUOTE_ALL make sure all your entries are quoted like this: "value1","value2","value3"when using csv.QUOTE_NONE it will give you: `value1, value2, value3

, . "somedata"user"somemoredata "somedata""user""somemoredata .csv

, (), \" .

  create=csv.writer(open("test.csv","wb"),quoting=csv.QUOTE_NONEescapechar='\\', quotechar='"')
for element in file:
    create.writerow(element)

somedata\"user\"somemoredata, . , .

0

All Articles