Python3 csv DictWriter:通过bz2写入失败(TypeError:' str' / buffer interface)

时间:2015-06-18 10:16:32

标签: python python-3.x python-3.4

我正在尝试在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行?还是有一个优雅的解决方案?

1 个答案:

答案 0 :(得分:4)

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