首页 > Python资料 博客日记

python 将文件夹里多个json文件合并成一个

2024-05-12 17:00:05Python资料围观214

这篇文章介绍了python 将文件夹里多个json文件合并成一个,分享给大家做个参考,收藏Python资料网收获更多编程知识

1.合并完成后成为一个列表

import os
import json

def merge_json_folder(folder_path, output_file):
    json_files = [f for f in os.listdir(folder_path) if f.endswith('.json')]  # 获取文件夹中的所有 JSON 文件路径

    merged_data = []  # 创建一个空列表,用于存储合并后的 JSON 数据

    for file in json_files:
        file_path = os.path.join(folder_path, file)  # 构建完整的文件路径
        with open(file_path, 'r') as json_file:
            data = json.load(json_file)  # 读取 JSON 文件并解析为 Python 对象
            merged_data.append(data)  # 将解析后的 JSON 数据添加到列表中

    # 将合并后的数据转换为 JSON 字符串
    merged_json = json.dumps(merged_data, indent=4)

    # 将合并后的 JSON 字符串写入目标文件
    with open(output_file, 'w') as output:
        output.write(merged_json)

    print("JSON 文件合并完成!")

# 使用示例
folder_path = "json_folder"  # 存放 JSON 文件的文件夹路径
output_file = "merged.json"  # 合并后的 JSON 文件路径
merge_json_folder(folder_path, output_file)

2.合并完成后保留原格式

import os
import json

def merge_json_folder(folder_path, output_file):
    json_files = [f for f in os.listdir(folder_path) if f.endswith('.json')]  # 获取文件夹中的所有 JSON 文件路径

    merged_data = []  # 创建一个空列表,用于存储合并后的 JSON 数据

    for file in json_files:
        file_path = os.path.join(folder_path, file)  # 构建完整的文件路径
        with open(file_path, 'r') as json_file:
            data = json_file.read()  # 读取 JSON 文件内容
            merged_data.append(data)  # 将 JSON 数据添加到列表中

    # 将列表中的 JSON 数据写入目标文件
    with open(output_file, 'w') as output:
        output.write('\n'.join(merged_data))

    print("JSON 文件合并完成!")

# 使用示例
folder_path = "json_folder"  # 存放 JSON 文件的文件夹路径
output_file = "merged.json"  # 合并后的 JSON 文件路径
merge_json_folder(folder_path, output_file)


版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐