Python - 如何一次性有效地写入/读取压缩档案中的 JSON 文件?

hpy*_*hpy 2 python compression performance json

我正在使用 Python 3.8,并且希望将数据字典保存到 JSON 文件中,该文件一次性压缩在存档中,最好仅使用 Python 标准库。例如,这意味着我的数据保存在data.jsonarchive 中包含的文件中compressed_data.zip

现在,这是我所得到的:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: GPL-3.0-or-later

# Python Standard Library imports

import json
import zlib

# Prepare some data
data: dict = {
    "common_name": "Brongersma's short-tailed python",
    "scientific_name": "Python brongersmai",
    "length": 290
}

# Save data to a JSON file
with open("data.json", "w", encoding="utf-8") as output_JSON_file: 
    json.dump(data, output_JSON_file, ensure_ascii=False, indent=4)

# Open saved JSON then compress it
with open ("data.json", "r", encoding="utf-8") as input_JSON_file: 
    data: dict = json.load(input_JSON_file)
    # Data needs to be saved as bytes to be compressed
    data_bytes: bytes = json.dumps(data, indent=4).encode("utf-8")
    compressed_data = zlib.compress(data_bytes, level=zlib.Z_BEST_COMPRESSION)
    with open ("compressed_data.zip" , "wb") as output_zlib_file: 
        output_zlib_file.write(compressed_data)
Run Code Online (Sandbox Code Playgroud)

这不会产生我想要的结果,因为(a)它首先保存 JSON 文件,打开它,然后将数据保存到压缩文件中,最终在磁盘上有两个文件;( b )压缩文件是压缩数据,而不是可以在任何通用GUI压缩/解压缩程序中打开的ZIP文件中的JSON文件。

所以我的问题是:

  1. 有没有一种方法可以一次性实现我的目标,而无需先保存 JSON 文件,然后将其压缩到存档中?(即.json文件从不接触磁盘,只有.zip文件接触磁盘)

  2. 如何执行相反操作并将存档直接解压缩到 Python 中的字典中?

  3. 如果没有办法一次性实现 1. 和 2.,那么什么是相对有效的方法呢?

注意:理想情况下,我想要一个仅使用 Python 3.8 标准库的解决方案,并且压缩存档不必使用该zlib库或成为 ZIP 文件。其他高压缩比方法也可以

谢谢你!

hpy*_*hpy 6

终于想通了。记录于此,以供日后参考。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: GPL-3.0-or-later

# Python's internal `zipfile` module
import json
import zipfile

# Prepare some data
data: dict = {
    "common_name": "Brongersma's short-tailed python",
    "scientific_name": "Python brongersmai",
    "length": 290
}

# Use the `zipfile` module
# `compresslevel` was added in Python 3.7
with zipfile.ZipFile("compressed_data.zip", mode="w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zip_file: 
    # Dump JSON data
    dumped_JSON: str = json.dumps(data, ensure_ascii=False, indent=4)
    # Write the JSON data into `data.json` *inside* the ZIP file
    zip_file.writestr("data.json", data=dumped_JSON)
    # Test integrity of compressed archive
    zip_file.testzip()
Run Code Online (Sandbox Code Playgroud)

该解决方案使用Python标准库的内部zipfile模块。关键是zip_file.writestr()它允许您实质上写入ZIP 文件内的文件。

如果还有其他解决方案,欢迎分享!