rakesh1 moorthy rakesh1 moorthy - 1 year ago 73
Python Question

Encoding issue when writing to CSV file in Python

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


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)

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

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download