『Python笔记』Python实现多个json文件合并到一个json文件!

Python学习笔记 专栏收录该内容
34 篇文章 5 订阅
Python实现多个json文件合并到一个json文件!

1. 代码

# !/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@author: kaifang zhang
@license: Apache License
@time: 2020/12/09
@contact: 1115291605@qq.com
"""
import os
import json
import tqdm


def merge_json(path_results, path_merges):
    """
    主要功能是实现一个目录下的多个json文件合并为一个json文件。
    :param path_results:
    :param path_merges:
    :return:
    """
    merges_file = os.path.join(path_merges, "bas_fund_transaction.json")
    with open(merges_file, "w", encoding="utf-8") as f0:
        for file in os.listdir(path_results):
            with open(os.path.join(path_results, file), "r", encoding="utf-8") as f1:
                for line in tqdm.tqdm(f1):
                    line_dict = json.loads(line)
                    js = json.dumps(line_dict, ensure_ascii=False)
                    f0.write(js + '\n')
                f1.close()
        f0.close()


if __name__ == '__main__':
    path_results, path_merges = "./results", "./results_merges"
    if not os.path.exists(path_merges):  # 如果results目录不存在,新建该目录。
        os.mkdir(path_merges)
    merge_json(path_results, path_merges)

  • 0
    点赞
  • 5
    评论
  • 9
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值