Learner Learner - 23 days ago 9
Python Question

'ascii' codec can't encode character error

I request your kind assistance in tackling an error. I am trying to save MS Access database tables as CSV files using Python. I seem to be running into an error I do not know how to fix. I have looked through different posts on Stack overflow and tried them but nothing fulfilling. Please provide your kind assistance.

import pyodbc
import csv

conn_string = ("DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\\Access\\permissions.accdb")

conn = pyodbc.connect(conn_string)

cursor = conn.cursor()

cursor.execute("select * from [Perm_Site Info];")

with open('C:\\Desktop\\Python Files\\Perms_Site_Info.csv','wb') as csvfile:
writer = csv.writer(csvfile)
rest_array = [text.encode("utf8") for text in cursor]
writer.writerow(rest_array)
writer.writerow([i[0] for i in cursor.description])
writer.writerows(cursor)

cursor.close()
conn.close()

print 'All done for now'


The error:

writer.writerows(cursor)
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 4: ordinal not in range(128)

Answer

You should probably install and use the unicodecsv module.

https://pypi.python.org/pypi/unicodecsv/0.14.1