rakesh1 moorthy rakesh1 moorthy - 2 months ago 8
Python Question

Encoding issue when writing to CSV file in Python

I have some encoding issue while writing an array to CSV.

Code:

import csv
a = [u'eNTfxfwc', 'Pushkar', 'Waghulde', 'pushkar.waghulde@gmail.com', 'Los Angeles', '', 'UNITED STATES', '2652 Ellendale Pl # 9', '', 'Los Angeles, UNITED STATES', u'90007', u'', u'(213)458-2091', u'None', u'', u'imports/jobvite/eNTfxfwc.txt', '07/17/2012', u'2012-24', u'pWOjJfww', u'Undefined', u'Import', u' ', '', '', u'\u8edf\u9ad4\u5de5\u7a0b\u5e2b (Software Engineer)', '07/17/2012', '', u'Undefined', '', u'None', '', '', u'Undefined', u'Not Considered', '', '07/17/2012', u'import/jobvite/eNTfxfwc_1.txt']


f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a).encode('utf-8')


How can I fix this issue and write array into CSV file?

Answer

Just encode the elements in a before writing them

a = [i.encode('utf-8') for i in a]

f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',',lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)
Comments