在文件中写入列时ASCII编码错误

时间:2016-07-12 21:43:54

标签: python python-2.7

rows = zip(recallid, recalldate, recallnums, name, model, ptype, categoryid, numberofunits)
with open('WIP.csv'.encode('utf-8'), 'wb') as f:
    writer = csv.writer(f)    
    for row in rows:
        writer.writerow(row)       #line 46

这个程序给我一个错误 - “UnicodeEncodeError:'ascii'编解码器不能编码位置8的字符u'\ xae':序数不在范围内(128)”

错误发生在第46行。

我无法识别错误。请有人帮我识别并纠正它。 原始列表仅包含字母,数字和符号。

1 个答案:

答案 0 :(得分:0)

您需要对数据进行编码,而不是文件名:

with open('WIP.csv', 'w') as f:
    writer = csv.writer(f)
    for row in rows:
        writer.writerow([s.encode("utf-8") for s in row])

如果您的某些数据不是字符串:

 writer.writerow([s.encode("utf-8") if isinstance(s, basestring) else s for s in row])