I am need to actually create a Windows INI using Python scipt file of below format:

AGENTIP = 1.2.3.4,
VARFILE = C:\Users\output\temp.out
INFOFILE= C:\Users\output\info.out
SYNTEST = Run:Level1/Get
CMDMODE = RUNTESTSUITE

And Below is my Python code where I have the data in JSON string and then dump the content in a file:

def change_test_details(self, ver, level, grp):
    data = {"AGENTIP" : "1.2.3.4", "VARFILE" : "C:\\Users\\output\\temp.out", "INFOFILE" : "C:\\Users\\output\\info.out", "SYNTEST" :"Run:Level1/Get", "CMDMODE" :"RUNTESTSUITE"}
    data["SYNTEST"] = ver + ":" + level + "/" + grp
    with open("a.txt", 'w') as outfile:
        json.dump(data, outfile,indent=2)

When the method is called with below param:

"BETA" "Level5" "Set"

The final output if the file is

{
  "AGENTIP": "1.2.3.4",
  "VARFILE": "C:\\Users\\output\\temp.out",
  "INFOFILE": "C:\\Users\\output\\info.out",
  "SYNTEST": "\"BETA\":\"Level5\"/\"Set\"",
  "CMDMODE": "RUNTESTSUITE"
}

There is '{ .. }' braces and extra double quotes and '\' and expected value of SYNTEST should be BETA:Level5/Set ?

How can change the JSON string to required format?

1 Answers

1
Shuvojit On Best Solutions

json.dump() prints an object as a json formatted string. So when you dump that into outfile you get a json string in the file, which is how it's supposed to behave.

What you want is to iterate over the items and print them according to the format you want.

def change_test_details(ver, level, grp):
    data = {"AGENTIP" : "1.2.3.4", "VARFILE" : "C:\\Users\\output\\temp.out", "INFOFILE" : "C:\\Users\\output\\info.out", "SYNTEST" :"Run:Level1/Get", "CMDMODE" :"RUNTESTSUITE"}
    data["SYNTEST"] = ver + ":" + level + "/" + grp
    with open("a.txt", 'w') as outfile:
        for k, v in data.items():
            outfile.write(f'{k} = {v}\n')

change_test_details("BETA", "Level5","Set")

When you run this, a.txt looks something like:

AGENTIP = 1.2.3.4
VARFILE = C:\Users\output\temp.out
INFOFILE = C:\Users\output\info.out
SYNTEST = BETA:Level5/Set
CMDMODE = RUNTESTSUITE