Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i quote escape characters in csv writer in python

Tags:

python

csv

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

like image 593
user2294401 Avatar asked Apr 26 '13 02:04

user2294401


1 Answers

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!"
like image 90
nad2000 Avatar answered Sep 27 '22 20:09

nad2000