Learner Learner - 10 months ago 58
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([i[0] for i in cursor.description])


print 'All done for now'

The error:

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

Answer Source

You should probably install and use the unicodecsv module.