【问题标题】:python tempfile + gzip + json dumppython tempfile + gzip + json 转储
【发布时间】:2020-03-12 19:59:20
【问题描述】:

我想使用 python3 (3.5) 将非常大的字典转储到压缩的 json 文件中。

import gzip
import json
import tempfile

data = {"verylargedict": True}

with tempfile.NamedTemporaryFile("w+b", dir="/tmp/", prefix=".json.gz") as fout:
    with gzip.GzipFile(mode="wb", fileobj=fout) as gzout:
        json.dump(data, gzout)

我得到了这个错误。

Traceback (most recent call last):
  File "test.py", line 13, in <module>
    json.dump(data, gzout)
  File "/usr/lib/python3.5/json/__init__.py", line 179, in dump
    fp.write(chunk)
  File "/usr/lib/python3.5/gzip.py", line 258, in write
    data = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'str'

有什么想法吗?

【问题讨论】:

    标签: python json python-3.x gzip temporary-files


    【解决方案1】:

    Gzip 对象没有文本模式。所以我会创建一个包装器作为文件句柄对象传递。这个包装器从 json 中获取数据并将其编码为二进制以写入 gzip 文件:

    class wrapper:
        def __init__(self,gzout):
            self.__handle = gzout
        def write(self,data):
            self.__handle.write(data.encode())
    

    这样使用:

    json.dump(data, wrapper(gzout))
    

    每次json.dump要写入对象时,都会调用wrapper.write方法,将文本转换为二进制并写入二进制流

    (来自io 模块的一些内置包装器可能也适合,但这种实现简单且有效)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-25
      • 2014-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多