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

标签 python json performance compression

我正在使用 Python 3.8,并且希望将数据字典保存到压缩在存档中的 JSON 文件一次性,最好仅使用 Python标准库。例如,这意味着我的数据保存在 data.json 文件中,该文件包含在存档 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)

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

所以我的问题是:

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

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

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

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

谢谢!

最佳答案

终于明白了。记录于此,以供日后引用。

#!/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()

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

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

关于Python - 如何一次性有效地写入/读取压缩文件中的 JSON 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65834655/

相关文章:

javascript - 如何使用 javascript 创建以下类型的 json 数组?

jquery - 如何使用没有外部名称的 .each 解析 json 数组?

python - 最快的列表索引搜索

python - python中的str性能

python - Pandas:当索引为年月且列为日时,将 DataFrame 转换为系列

Python 长文件名支持在 Windows 中损坏

python - 如何避免从元类派生的动态生成的类最终不会成为同一个类?

python - 如何在 Python 中创建示例单列 Spark DataFrame?

ios - Swift 中的 Google 日历 API

performance - 什么对性能更好,对象元胞数组还是异构数组?