Python:如何从压缩的 json .gz 文件中读取并写入 json 文件

Posted

技术标签:

【中文标题】Python:如何从压缩的 json .gz 文件中读取并写入 json 文件【英文标题】:Python: How to read from compressed json .gz file and write to json file 【发布时间】:2021-12-15 17:06:58 【问题描述】:

我想从压缩的 .json.gz 文件中读取并将其解码后的文件写入 .json 文件

.json.gz 文件:

数据/sample1.gz data/sample2.gz

写入 .json 文件

数据/sample1.json 数据/sample2.json

【问题讨论】:

这能回答你的问题吗***.com/questions/12902540/… 不,它不能解决我的问题 您需要在您的解决方案中使用 Spark 吗?我注意到你标记了 pyspark,但问题本身根本没有提到它。 是的,我有一个包含 .gz 文件的目录。我需要把它读入火花。 【参考方案1】:

我有一个要求,我有一个压缩 json .gz 文件的列表。我需要将其解压缩并将其转换回具有相同文件名的 json 文件。下面提到的代码正在运行。

将此脚本放在包含 .gz 文件的文件夹中,然后使用 python3 运行它。它会起作用的。

文件:script.py

import gzip
import os

def get_file_names_by_extension(path = ".", file_extension = ".gz"):
    file_names = []
    for x in os.listdir(path):
        if x.endswith(file_extension):
            file_names.append(x)
    return file_names

def write_file(data, destination_path, file_name, encoding = "utf-8"):
    output_file_name = "/".join([destination_path, file_name])
    print(output_file_name)
    with open(output_file_name, "w") as outfile:
        outfile.write(data.encode(encoding))

def decompress_files(files, destination_path, output_format = ".json", encoding = "utf-8"):
    for file in files:
        _file = gzip.GzipFile(file, "rb")
        content = _file.read()
        content = content.decode(encoding)
        output_file_name = "".join([file.split(".")[0], output_format])
        write_file(content, destination_path, output_file_name, encoding)

        
files = get_file_names_by_extension(path=".", file_extension=".gz")
decompress_files(files, ".", ".json")

【讨论】:

【参考方案2】:

Pyspark 可以从文件名中推断出 json 文件是 gzip 压缩的。您可以读取数据,然后在不进行任何压缩的情况下将其写回,以获得您想要的结果。在 Spark 中这样做的好处是它可以使用多个 worker 并行读取/写入数据,尤其是当数据在 S3 中时。

df = spark.read.json("data/")
df.write.json("data/", mode="append", compression="none")

【讨论】:

以上是关于Python:如何从压缩的 json .gz 文件中读取并写入 json 文件的主要内容,如果未能解决你的问题,请参考以下文章

从 tar.gz 文件夹中读取 json 文件并转换为 pandas 数据框 [重复]

如何使用 python 读取压缩文件夹文件?

如何使用 Python 创建完整的压缩 tar 文件?

如何打开.json.gz格式文件并创建数据帧n R?

如何解压缩从 iPhone 上的服务器接收到的 gzip 文件?

如何在水壶中解压缩和导入 .tar.gz 文件?