【问题标题】:Django encoding problems with CSVCSV 的 Django 编码问题
【发布时间】:2016-08-17 18:28:36
【问题描述】:

文件导出效果很好,但我在编码数据时遇到了问题。 我哪里出错了?

我的代码是

for user in users:
    result = user[0].encode('utf-8')
    for x in filter(lambda q: q is not None, user):
        result += ', '
        if type(x) in (str, unicode):
            result += x.encode('utf-8')
        else:
            result += str(x)
        print type(result), result
    writer.writerow(result)

return response

【问题讨论】:

  • 您的问题到底是什么?您收到错误消息吗?
  • 定义“我有问题”。您收到错误/回溯吗?展示下。 CSV 因在 Python 2 库中不能很好地处理 Unicode 而臭名昭著,所以很多人使用unicodecsv。您使用的是 Python 2 还是 3?这里没有足够的信息来帮助你......
  • 不,我在导出文件时遇到问题。我正在使用 python 2.7 现在,文件中的数据看起来像 Имя Фамилия Комментарий Дата контракта � � � � � � �

标签: python django csv encoding decoding


【解决方案1】:

.encode 方法应用于 Unicode 字符串以生成字节字符串;如果您的 CSV 数据不在 utf-8 中,而是在 latin-1 中编码,那么您需要“转码”。像这样的:

line.decode('latin-1').encode('utf-8')

如果您知道 CSV 编码,则将 latin-1 替换为您的输入数据编码。

另外,如果您不确定 CSV 文件的编码是什么,那么您可能需要考虑使用 chardet,您可以在 readthedocs 了解如何使用它

【讨论】:

  • 我使用了writer.writerow([x.encode('utf-8') for x in filter(lambda q: q is not None, user)]),但是这种方法不适用于所有值
猜你喜欢
  • 2017-12-04
  • 1970-01-01
  • 1970-01-01
  • 2015-01-24
  • 2021-02-26
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 2019-08-10
相关资源
最近更新 更多