python中的编码问题如何解决它

时间:2016-09-01 07:04:42

标签: python encoding utf

将数据写入csv文件

时出现此错误
import csv
a = [u'eaTfxfwz', u'Edward', u'O\u2019Connell', u'ejoconnell@sbcglobal.net', u'Santa Clara', u'CA', 'UNITED STATES', u'150 Saratoga Avenue #306', u'', u'Santa Clara, CA', u'95051', u'', u'408-835-2209', u'None', u'', '', u'2012-010', u'pjOjJfwT', u'Undefined', u'Import', u'     ', ' San Jose HQ, CA ', '', '', u'Undefined', '', u'None', '', '', u'Undefined', u'Not Considered', '', u'']
f3 = open('test.csv', 'at')
writer = csv.writer(f3,delimiter = ',', lineterminator='\n',quoting=csv.QUOTE_ALL)
writer.writerow(a)

错误

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 1: ordinal not in range(128)

如何修复

2 个答案:

答案 0 :(得分:0)

您可以使用utf-8编码。

import csv
aenc=[]
a = [u'eaTfxfwz', u'Edward', u'O\u2019Connell', u'ejoconnell@sbcglobal.net', u'Santa Clara', u'CA', 'UNITED STATES', u'150 Saratoga Avenue #306', u'', u'Santa Clara, CA', u'95051', u'', u'408-835-2209', u'None', u'', '', u'2012-010', u'pjOjJfwT', u'Undefined', u'Import', u'     ', ' San Jose HQ, CA ', '', '', u'Undefined', '', u'None', '', '', u'Undefined', u'Not Considered', '', u'']
for x in a:
    aenc.append(x.encode('utf-8'))
with open('test.csv', 'wb') as f3:
    writer = csv.writer(f3,delimiter = ',', lineterminator='\n', quoting=csv.QUOTE_ALL)
    writer.writerow(aenc)

答案 1 :(得分:0)

import csv
aenc = []

a = [u'eaTfxfwz', u'Edward', u'O\u2019Connell', u'ejoconnell@sbcglobal.net', u'Santa Clara', u'CA', 'UNITED STATES', u'150 Saratoga Avenue #306', u'', u'Santa Clara, CA', u'95051', u'', u'408-835-2209', u'None', u'', '', u'2012-010', u'pjOjJfwT', u'Undefined', u'Import', u'     ', ' San Jose HQ, CA ', '', '', u'Undefined', '', u'None', '', '', u'Undefined', u'Not Considered', '', u'']

for x in a:
    aenc.append(x.encode('utf-8'))

with open('test.csv', 'wb') as f3:
    writer = csv.writer(f3,delimiter = ',', lineterminator='\n', quoting=csv.QUOTE_ALL)

    writer.writerow(aenc)