我实际上需要使用以下格式的Python scipt文件创建Windows INI:
AGENTIP = 1.2.3.4,
VARFILE = C:\Users\output\temp.out
INFOFILE= C:\Users\output\info.out
SYNTEST = Run:Level1/Get
CMDMODE = RUNTESTSUITE
下面是我的Python代码,其中我将数据存储在JSON字符串中,然后将内容转储到文件中:
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)
使用以下参数调用该方法时:
“ BETA”“ Level5”“ Set”
最终输出,如果文件是
{
"AGENTIP": "1.2.3.4",
"VARFILE": "C:\\Users\\output\\temp.out",
"INFOFILE": "C:\\Users\\output\\info.out",
"SYNTEST": "\"BETA\":\"Level5\"/\"Set\"",
"CMDMODE": "RUNTESTSUITE"
}
有'{..}'大括号和双引号,并且'\'和SYNTEST的期望值应为 BETA:Level5 / Set ?
如何将JSON字符串更改为所需格式?
答案 0 :(得分:1)
json.dump()将对象打印为json格式的字符串。因此,当您将其转储到outfile中时,您会在文件中得到一个json字符串,这就是它的行为方式。
您想要的是遍历所有项目,并根据所需格式打印它们。
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")
运行此命令时,a.txt类似于:
AGENTIP = 1.2.3.4
VARFILE = C:\Users\output\temp.out
INFOFILE = C:\Users\output\info.out
SYNTEST = BETA:Level5/Set
CMDMODE = RUNTESTSUITE