Varen Gupta Varen Gupta - 10 months ago 59
Python Question

ASCII encode error while writing columns in a file

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

This program gives me an error as - "UnicodeEncodeError: 'ascii' codec can't encode character u'\xae' in position 8: ordinal not in range(128)"

error occurs at line 46.

I am unable to identify error. Please someone help me identify and rectify it.
Original list contains only alphabets, numbers and symbols.


You need to encode the data, not the filename:

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])

If some of your data are not strings:

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