我想使用 Python 的 csv
模块中的 DictWriter
生成一个使用 GZip 压缩的 .csv 文件。我需要全部在内存中执行此操作,因此无法使用本地文件。
但是,我在处理 Python 3 中每个模块的类型要求时遇到了麻烦。假设我正确地获得了一般结构,我不能让两个模块一起工作,因为 DictWriter
需要写到 io.StringIO
缓冲区,而 GZip
需要一个 io.BytesIO
对象。
所以,当我尝试这样做时:
buffer = io.BytesIO()
compressed = gzip.GzipFile(fileobj=buffer, mode='wb')
dict_writer = csv.DictWriter(buffer, ["a", "b"], extrasaction="ignore")
我得到:
TypeError:需要一个类似字节的对象,而不是“str”
并且尝试将 io.StringIO
与 GZip
一起使用也不起作用。我该怎么做?
最佳答案
您可以使用 io.TextIOWrapper
将文本流无缝转换为二进制流:
import io
import gzip
import csv
buffer = io.BytesIO()
with gzip.GzipFile(fileobj=buffer, mode='wb') as compressed:
with io.TextIOWrapper(compressed, encoding='utf-8') as wrapper:
dict_writer = csv.DictWriter(wrapper, ["a", "b"], extrasaction="ignore")
dict_writer.writeheader()
dict_writer.writerows([{'a': 1, 'b': 2}, {'a': 4, 'b': 3}])
print(buffer.getvalue()) # dump the compressed binary data
buffer.seek(0)
dict_reader = csv.DictReader(io.TextIOWrapper(gzip.GzipFile(fileobj=buffer, mode='rb'), encoding='utf-8'))
print(list(dict_reader)) # see if uncompressing the compressed data gets us back what we wrote
这个输出:
b'\x1f\x8b\x08\x00\x9c6[\\\x02\xffJ\xd4I\xe2\xe5\xe52\xd41\x02\x92&:\xc6@\x12\x00\x00\x00\xff\xff\x03\x00\x85k\xa2\x9e\x12\x00\x00\x00'
[OrderedDict([('a', '1'), ('b', '2')]), OrderedDict([('a', '4'), ('b', '3')])]
关于python - 使用 csv.DictWriter 输出内存中的 gzip 压缩 csv 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54559843/