Python3 csv DictWriter: writing through bz2 fails (TypeError: 'str'/buffer interface)

Python3 csv DictWriter: writing through bz2 fails (TypeError: 'str'/buffer interface)

我正在尝试在 python3 中编写一个即时 bz2 压缩的 csv 文件。

没有压缩这工作正常:

from csv import DictWriter

FIELDNAMES = ('a', 'b')
OUT_CSV = 'out.csv'

DATA = ({'a': 1, 'b': 2}, {'a':3, 'b':4})

# works fine
with open(OUT_CSV, 'w') as file_pointer:
    csv_writer = DictWriter(file_pointer, fieldnames=FIELDNAMES)
    csv_writer.writeheader()
    for dataset in DATA:
        csv_writer.writerow(dataset)

添加压缩失败:

from csv import DictWriter
import bz2

FIELDNAMES = ('a', 'b')
OUT_BZ2 = 'out.csv.bz2'

DATA = ({'a': 1, 'b': 2}, {'a':3, 'b':4})

# this fails
with bz2.open(OUT_BZ2, mode='w', compresslevel=9) as file_pointer:
    csv_writer = DictWriter(file_pointer, fieldnames=FIELDNAMES)
    csv_writer.writeheader() # fails here; raises "TypeError: 'str' does not support the buffer interface"
    for dataset in DATA:
        csv_writer.writerow(dataset)

例外情况:TypeError: 'str' does not support the buffer interface

是否有缓冲区兼容的 csv 模块?还是我必须手写 csv 行?或者有没有优雅的解决方案?

请注意,bz2.open 默认为二进制模式。这与默认为文本模式的常规 Python 内置 open 形成对比。要解决您的错误,您只需要以文本模式打开文件,而不是默认的二进制模式。将 with bz2.open(... mode='w'...) 更改为 with bz2.open(... mode='wt'...)。我在 Python 3.4.

上测试过