gpt4 book ai didi

python-3.x - json.dump 到 python 3 中的 gzip 文件

转载 作者:行者123 更新时间:2023-12-03 23:56:44 33 4
gpt4 key购买 nike

我正在尝试一步将一个对象写入一个 gzip 压缩的 json 文件(最小化代码,并可能节省内存空间)。我最初的想法(python3)是这样的:

import gzip, json
with gzip.open("/tmp/test.gz", mode="wb") as f:
json.dump({"a": 1}, f)

然而这失败了: TypeError: 'str' does not support the buffer interface ,我认为这与未编码为字节的字符串有关。那么这样做的正确方法是什么?

我不满意的当前解决方案:

以文本模式打开文件解决了这个问题:
import gzip, json
with gzip.open("/tmp/test.gz", mode="wt") as f:
json.dump({"a": 1}, f)

但是我不喜欢文本模式。在我看来(也许这是错误的,但 this 支持),文本模式用于修复行尾。这不应该是一个问题,因为 json 没有行尾,但我不喜欢它(可能)弄乱我的字节,它(可能)更慢,因为它正在寻找行尾来修复,并且(最糟糕的是)全部)我不明白为什么关于行尾的某些东西可以解决我的编码问题?

最佳答案

题外话 :我应该比最初更深入地研究文档。

python docs展示:

Normally, files are opened in text mode, that means, you read and write strings from and to the file, which are encoded in a specific encoding (the default being UTF-8). 'b' appended to the mode opens the file in binary mode: now the data is read and written in the form of bytes objects. This mode should be used for all files that don’t contain text.



我不完全同意 json 编码的结果是一个字符串(我认为它应该是一组字节,因为它明确定义了它使用 utf-8 编码),但我之前注意到了这一点。所以我猜它是文本模式。

关于python-3.x - json.dump 到 python 3 中的 gzip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30297889/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com