Python 3 DictWriter csv BytesIO TypeE

2024-04-20 09:40:49 发布

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

我使用python3尝试在文件上生成csv。 我想确保我写的是utf8,所以我把dict列表的值转换成字节字符串

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()呼叫

^{pr2}$

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


Tags: 文件csvinfield列表foroutput字节
1条回答
网友
1楼 · 发布于 2024-04-20 09:40:49

csvmdoule根据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')

相关问题 更多 >