合并json文件或者统计json文件的方法

如果你想要累加或者统计json数据,或者想要使用json方法都可以参考这个文章

import os
# from __future__ import unicode_literals
import json
finally_result = dict()

def combine(json_file_dir,previous_file_path,finally_file_path):
    for root, dirs, files in os.walk(json_file_dir):
        for file in files:
            path = os.path.join(root, file)
            with open(path, "r",encoding="utf-8") as f:
                data = json.loads(f.read())
                for key, value in data.items():
                    print(type(key),"key")
                    print(type(value),"value")
                    if key not in finally_result:
                        finally_result[key] = int(value)
                    else:
                        finally_result[key] += int(value)

    # 读取之前存在的结果
    if os.path.exists(previous_file_path):
        with open(previous_file_path, "r",encoding="utf-8") as f:
            print(type(f.read()))
            data = json.loads(f.read())
            if data:
                for key, value in data:
                    if key not in finally_result:
                        finally_result[key] = int(value)
                    else:
                        finally_result[key] += int(value)
    # 写入最终的新数据到本地
    with open(finally_file_path,"w",encoding="utf-8") as f:
        f.write(json.dumps(finally_result,ensure_ascii=False,indent=2))  # ensure_ascii 是否使用ascii编码,设置为False,编码格式改为utf-8

if __name__ == '__main__':
    json_file_dir = "./data"
    previous_file_path = "./result_file.json"
    finally_file_path = "./result_file.json"
    combine(json_file_dir,previous_file_path,finally_file_path)

你可能感兴趣的:(合并json文件或者统计json文件的方法)