Python筆記:python實現多個json檔案合併到一個json檔案!
阿新 • • 發佈:2020-12-23
技術標籤:Python學習筆記pythonjson
python實現多個json檔案合併到一個json檔案! |
1. 程式碼
# !/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@author: kaifang zhang
@license: Apache License
@time: 2020/12/09
@contact: [email protected]
"""
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)