[python]更新json格式的文件

一、需求:
遍历src文件夹下的路径,
1.如果dest路径下没有这个文件,拷贝这个文件到dest路径
2.如果dest路径下有这个文件,跟新src下的文件内容插入/修改 到dest下的文件。

二、方法:

========================
#!/usr/bin/env python3
import json

result = []
file_1 = ‘dest.json’
file_2 = ‘merge.json’
file_3 = ‘new.json’
#读取文件file_1,到result
with open(file_1, “r”) as infile:
result = json.load(infile)
print(result)

#读取文件file_2,加载到result
with open(file_2, “r”) as infile_2:
result.update(json.load(infile_2))
print(result)

#按照json格式把result 写入file_3, PS:indent=4排版
with open(file_3, “w”) as outfile:
outfile.write(json.dumps(result), indent=4)
==============================

三、运行结果:

在这里插入图片描述

file1(dest.json)
{
“int_type”:12,
“string_type”:“abc”,
“int_array”:[9.8,-7.7,66],
“string_array”:[“hello”,“world”,“welcome”,“dalian”],
“object_type”:{
“int_aa”:2,
“str_bb”:“gege”
},
“object_array”:[
{
“object1”:111
},
{
“object2”:“222”
}
]
}

==============
file_2(merge.json)
{
“string_type”:“test_modify”,
“int_array”:[9.8,-7.7,66,999],
“string_array”:[“hello”,“modify”],
“object_type”:{
“int_aa”:88,
“new”:“test_new”
},
“object_array”:[
{
“object1”:111,
“object2”:“222”
}
],
“new”:“test”
}

=============
file_3(new.json)
{
“int_type”: 12,
“string_type”: “test_modify”,
“int_array”: [
9.8,
-7.7,
66,
999
],
“string_array”: [
“hello”,
“modify”
],
“object_type”: {
“int_aa”: 88,
“new”: “test_new”
},
“object_array”: [
{
“object1”: 111,
“object2”: “222”
}
],
“new”: “test”
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值