使用CSV的Django编码问题

2024-07-07 08:59:28 发布

您现在位置:Python中文网/ 问答频道 /正文

文件导出工作正常,但我在编码数据时遇到问题。 我哪里出错了?在

我的代码是

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

Tags: 文件lambda代码inforistyperesult
1条回答
网友
1楼 · 发布于 2024-07-07 08:59:28

.encode方法应用于Unicode字符串以生成字节字符串;如果您的CSV数据不是utf-8格式,而是使用拉丁语1进行编码,那么您需要一个“代码转换”。像这样:

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

如果你知道你的CSV编码,那么用你的输入数据编码替换拉丁语-1。在

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

相关问题 更多 >