我想将包含 Unicode 值的嵌套列表转换为 latin-1 编码的 csv(以便我可以在 Web 响应中传输结果并让最终用户的本地 Excel 打开文件)。
我们正在过渡到 Py3,因此最好是相同的代码需要为 Py2 和 Py3 工作(出于维护和覆盖原因)。
我们的 Python 2 代码(用于 py2):
from cStringIO import StringIO
def rows_to_csv_data(rows):
rows = [[col.encode('latin-1') for col in row] for row in rows]
buf = StringIO()
writer = csv.writer(buf)
writer.writerows(rows)
return buf.getvalue()
一个简单的测试用例:
def test_rows_to_csv_data():
rows = [
[u'helloæ', u'worldø']
]
binary_data = rows_to_csv_data(rows)
assert binary_data == u"helloæ,worldø\r\n".encode('latin-1')
# Update: the data is never written to a file, but sent with a web response:
response = http.HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=hello.csv'
response.write(binary_data)
assert response.serialize() == b'Content-Type: text/csv\r\nContent-Disposition: attachment; filename=hello.csv\r\n\r\nhello\xe6,world\xf8\r\n'
我找不到任何方便的方法来使用未来或六个库来做到这一点。
使用from io import StringIO给了我(Py3):
Expected :b'hello\xe6,world\xf8\r\n'
Actual :b'hello\\xe6',b'world\\xf8'\r\n
和 Py2:
> writer.writerows(rows)
E TypeError: unicode argument expected, got 'str'
使用from io import BytesIO as StringIO适用于 Py2,但 Py3 给出:
rows = [[b'hello\xe6', b'world\xf8']]
def rows_to_csv_data(rows):
rows = [[col.encode('latin-1') for col in row] for row in rows]
buf = StringIO()
writer = csv.writer(buf)
> writer.writerows(rows)
E TypeError: a bytes-like object is required, not 'str'
这是我在这种情况下不理解的错误消息......
是否可以编写一个适用于两种 Python 的函数,或者我是否需要一个完全独立的 Py3 函数?