python - 使用 csv.DictWriter 输出内存中的 gzip 压缩 csv 文件?

标签 python python-3.x csv io gzip

我想使用 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.StringIOGZip 一起使用也不起作用。我该怎么做?

最佳答案

您可以使用 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/

相关文章:

python - 为什么 n=[1,2,3,4,5,6,7,8],n[ :6:-2] is [8] in Python?

python - 如何列出 tar 文件的内容而不在 python 中提取它?

python - 这个查询如何按关键字匹配的数量排序?

python-3.x - 如何通过从特定列创建分组多标题来 reshape 数据框?

java - Android 写入 CSV RAM 问题

python - 在 scipy 中找到卡方检验的自由度?

python-3.x - alsaaudio 库不工作

python-3.x - 如何根据特定条件替换 Pandas Dataframe 中特定列的特定值?

regex - 正则表达式查找用逗号分隔的字符串,然后添加引号?

parsing - 如何以编程方式猜测 CSV 文件是逗号分隔还是分号分隔