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

谁践踏了优雅 2022-12-29 12:59 489阅读 0赞






Python实现多个json文件合并到一个json文件!

1. 代码

  1. # !/usr/bin/env python
  2. # -*- encoding: utf-8 -*-
  3. """
  4. @author: kaifang zhang
  5. @license: Apache License
  6. @time: 2020/12/09
  7. @contact: 1115291605@qq.com
  8. """
  9. import os
  10. import json
  11. import tqdm
  12. def merge_json(path_results, path_merges):
  13. """
  14. 主要功能是实现一个目录下的多个json文件合并为一个json文件。
  15. :param path_results:
  16. :param path_merges:
  17. :return:
  18. """
  19. merges_file = os.path.join(path_merges, "bas_fund_transaction.json")
  20. with open(merges_file, "w", encoding="utf-8") as f0:
  21. for file in os.listdir(path_results):
  22. with open(os.path.join(path_results, file), "r", encoding="utf-8") as f1:
  23. for line in tqdm.tqdm(f1):
  24. line_dict = json.loads(line)
  25. js = json.dumps(line_dict, ensure_ascii=False)
  26. f0.write(js + '\n')
  27. f1.close()
  28. f0.close()
  29. if __name__ == '__main__':
  30. path_results, path_merges = "./results", "./results_merges"
  31. if not os.path.exists(path_merges): # 如果results目录不存在,新建该目录。
  32. os.mkdir(path_merges)
  33. merge_json(path_results, path_merges)

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2FiYzEzNTI2MjIyMTYw_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,489人围观)

还没有评论,来说两句吧...

相关阅读