【发布时间】:2018-09-07 03:53:23
【问题描述】:
Here 是关于如何使用json.dumps 写入 gzip 文件的一个很好的答案。我想做的是使用dump方法直接将json序列化为GzipFile对象。
示例代码:
import gzip, json
data = # a dictionary of data here
with gzip.open(write_file, 'w') as zipfile:
json.dump(data, zipfile)
引发的错误是
TypeError: memoryview: a bytes-like objet is required, not 'str'
我相信这是因为 gzip write() 方法需要一个字节对象传递给它。根据documentation,
json 模块总是生成 str 对象,而不是 bytes 对象。 因此,fp.write() 必须支持 str 输入。
有没有办法将json 字符串输出包装为字节,以便GzipFile 的write() 处理它?或者是这样做的唯一方法是使用json.dumps 和encode() 将结果字符串转换为字节对象,就像在另一个链接的答案中一样?
【问题讨论】:
-
你能试试 data =b'' #data here'' 吗?看看它是否适合你?
-
@toheedNiaz 我澄清了问题以表明数据是字典。
标签: python json python-3.x gzip