【问题标题】:'ascii' codec can't encode character error“ascii”编解码器无法编码字符错误
【发布时间】:2017-03-31 05:21:30
【问题描述】:

我请求您协助解决错误。我正在尝试使用 Python 将 MS Access 数据库表保存为 CSV 文件。我似乎遇到了一个我不知道如何解决的错误。我浏览了有关堆栈溢出的不同帖子并尝试了它们,但没有任何满足感。请提供您的帮助。

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'

错误:

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

【问题讨论】:

  • 您是否搜索过以前的此类问题?有一个是相同的,使用 Python 2.x 解决方案,这里是stackoverflow.com/q/40619675/4451406
  • 我已经编辑了我的 sn-p 以显示建议。我尝试了链接 Irmen 上的建议,但它给出了另一条信息。 rest_array = [text.encode("utf8") for text in cursor] AttributeError: 'pyodbc.Row' 对象没有属性 'encode'
  • 首先将结果行转换为适当的 str 类型。您正在尝试将 Row 结果对象直接写入 csv
  • Irmen,对不起,如果这听起来很业余(我是 Python 初学者),我该怎么做。
  • @Learner,你试过unicodecsv模块吗?

标签: python csv ms-access pyodbc


【解决方案1】:

您可能应该安装和使用 unicodecsv 模块。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-03
    • 2019-09-01
    • 1970-01-01
    • 2016-02-12
    • 2015-10-21
    • 2010-12-11
    • 2012-07-02
    相关资源
    最近更新 更多