【问题标题】:ASCII encode error while writing columns in a file在文件中写入列时出现 ASCII 编码错误
【发布时间】:2016-11-15 07:31:58
【问题描述】:
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' codec can't encode character u'\xae' in position 8: ordinal not in range(128)”

错误发生在第 46 行。

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

【问题讨论】:

  • 在 python 3.x 中,encoding 是一个可以传递给open 函数的参数。您正在对文件名进行编码。
  • 我理解你的意思,我正在编码我的文件名。所以删除了它。但是我在哪里放编码呢?还要提一下我在 python 2.7 上。

标签: python python-2.7


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多