Python 3 DictWriter csv BytesIO 类型错误

标签 python string csv python-3.x encoding

我正在使用 python 3 尝试在文件上生成 csv。 我想确保我正在编写 utf8,所以我正在将我的字典列表的值转换为字节字符串

field_order = ['field1', 'field2', 'field3', 'field4']
stats = ... # list of dicts
output = io.BytesIO()
writer = csv.DictWriter(output, field_order)
writer.writeheader()
for stats in my_stats:
    writer.writerow({k: bytes(v, 'utf8') for k, v in stats.items()})
    csv_output = output.getvalue()

我在 writer.writeheader() 调用中遇到异常

TypeError: 'str' does not support the buffer interface

似乎没有任何方法可以更改 writerheader 以写入字节。 我做错了什么?

最佳答案

csv mdoule 根据 the documentation 对字符串进行操作:

Writer objects (DictWriter instances and objects returned by the writer() function) have the following public methods. A row must be a sequence of strings or numbers for Writer objects and a dictionary mapping fieldnames to strings or numbers (by passing them through str() first) for DictWriter objects. Note that complex numbers are written out surrounded by parens. This may cause some problems for other programs which read CSV files (assuming they support complex numbers at all).

如何使用io.StringIO,然后将其编码为utf-8

import csv
import io

field_order = ['field1', 'field2', 'field3', 'field4']
my_stats = ...
output = io.StringIO()
writer = csv.DictWriter(output, field_order)
writer.writeheader()
for stats in my_stats:
    writer.writerow(stats)
csv_output = output.getvalue().encode('utf-8')

关于Python 3 DictWriter csv BytesIO 类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24968222/

相关文章:

php - 通过 PHP 导出为 CSV

python - 用 U2Net 去除背景太强了

C - 垃圾字符,即使有空终止符,结构

bash 中的字符串替换 (${s//$foo/$bar}) 不适用于反斜杠

c++ - 在 C++ 中传递 C 字符串的问题

c# - csv文件转xls文件时兼容性检查怎么解决?

python - 连接两个 csv 文件

python - 在 0.0.0.0 :8000 上运行 django

python - 从数据存储加载数据集并合并到单个字典中。资源问题

python - Alembic 忽略特定表