栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 追加json文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 追加json文件

python将json对象映射为集合,因此对json文件的追加写入,就直接变为对集合的更新操作。
import json
#导入json包

data={}
#创建一个data集合用于接收并暂存数据

json_list=["cls_FinancialClassification_answer.json",
           "cls_MedicalClassification_answer.json",
           "intent_InsuranceIntentChange_answer.json",
           "intent_InsuranceIntentConsult_answer.json",
           "intent_InsuranceIntentSearch_answer.json",
           "nli_FinancialNLI_answer.json",
           "nli_MedicalNLI_answer.json",
           "senti_FinancialSentiment_answer.json",
           "sts_FinancialSimilarity_answer.json",
           "sts_MedicalSimilarity_answer.json"
           ]
#需要追加的json文件列表



此处需要提前创建并声明data的数据类型为集合,以保证之后更新操作的正确性。

遍历需要追加写入的json_list,并逐个更新到data集合中。

此处需要强调,如果json文件中有中文,需要 encoding='utf-8'

for json_file in json_list:    
    with open(json_file,encoding='utf-8') as f:
        data.update(json.load(f))

使用json.dump方法将data集合输出为json文件。

#输出answer.json文件
with open('answer.json','w',encoding='utf-8') as w_f:
    json.dump(data,w_f,ensure_ascii=False,indent=2)

完整代码:

import json

data={}

json_list=["cls_FinancialClassification_answer.json",
           "cls_MedicalClassification_answer.json",
           "intent_InsuranceIntentChange_answer.json",
           "intent_InsuranceIntentConsult_answer.json",
           "intent_InsuranceIntentSearch_answer.json",
           "nli_FinancialNLI_answer.json",
           "nli_MedicalNLI_answer.json",
           "senti_FinancialSentiment_answer.json",
           "sts_FinancialSimilarity_answer.json",
           "sts_MedicalSimilarity_answer.json"
           ]

for json_file in json_list:    
    with open(json_file,encoding='utf-8') as f:
        data.update(json.load(f))


#输出answer.json文件
with open('answer.json','w',encoding='utf-8') as w_f:
    json.dump(data,w_f,ensure_ascii=False,indent=2)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/890088.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号