簡體   English   中英

python-if和elif的輸出寫入json文件

[英]python - output from if and elif write to json file

我試圖找到文件之間的區別,並獲得輸出。 但是如果有人可以幫助我,我該如何再次將其寫入新的json文件。 這是我的代碼

def check(a,b):
    diff = False
    for a_key in a:
        if a_key not in b:
            diff = True
            #print "key %s in a, but not in b" %a_key
            print a_key,a[a_key]
        elif a[a_key] != b[a_key]:
            diff = True
            #print "key %s in a and in b, but values differ (%s in a and %s in b)" %(a_key, a[a_key], b[a_key])
            print a_key,b[a_key]
    if not diff:
        print "both files are identical"

我想將輸出寫入json文件,而不是在控制台上打印。 我在打印后嘗試了此操作,但不希望使用o / p。 任何幫助表示贊賞。

res=a_key,b[a_key]
out_file = open("out.json","a")
json.dump(res,out_file, indent=4)
out_file.close()

這是示例文件。 文件1:

{
"abc": [
    "build=1.0.44.0", 
    "proxy=none"
], 
"xyz": [
    "proxy=none", 
    "build=1.0.129.0"
], 
"lmn": [
    "build=1.0.127.0", 
    "proxy=none"
], 
"test": [
    "build=1.0.144.0", 
    "proxy=http"
], 
"alfa": [
    "build=1.0.22.0", 
    "proxy=http"
], 
"beta": [
    "proxy=http",
    "build=1.0.17.0"
]
}

這是File2:

{
"abc": [
    "build=1.0.43.0", 
    "proxy=none"
], 
"xyz": [
    "proxy=none", 
    "build=1.0.128.0"
], 
"lmn": [
    "build=1.0.127.0", 
    "proxy=none"
], 
"test": [
    "build=1.0.141.0", 
    "proxy=http"
], 
"alfa": [], 
"beta": [
    "proxy=http",
    "build=1.0.17.0"
]
}

最終預期輸出:

{
"abc": "1.0.44.0", 
"xyz": "1.0.129.0",
"test":"1.0.144.0", 
"alfa":"1.0.22.0"
}
A = {"abc":["build=1.0.44.0","proxy=none"],"xyz":["proxy=none","build=1.0.129.0"],"lmn":["build=1.0.127.0","proxy=none"],"test":["build=1.0.144.0","proxy=http"],"alfa":["build=1.0.22.0","proxy=http"],"beta":["proxy=http","build=1.0.17.0"]}

B = {"abc":["build=1.0.43.0","proxy=none"],"xyz":["proxy=none","build=1.0.128.0"],"lmn":["build=1.0.127.0","proxy=none"],"test":["build=1.0.141.0","proxy=http"],"alfa":[],"beta":["proxy=http","build=1.0.17.0"]}


import json
def check(a,b):
    diff = False

    output = {}

    for a_key in a:
            if a_key not in b:
                diff = True
                output[a_key] = a[a_key][0]
            elif a[a_key] != b[a_key]:
                diff = True
                for v in a[a_key]:
                    if 'build=' in v:
                        output[a_key] = v.replace('build=','')
    if not diff:
            print ("both files are identical")
    else:
        print(output)
        with open("output.json","w") as outfile:
            outfile.write(json.dumps(output))


check(A,B)

輸出:

{"xyz": "1.0.129.0", "alfa": "1.0.22.0", "abc": "1.0.44.0", "test": "1.0.144.0"}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM