一、需求:
遍历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”
}