我正在将json文件写入键值属性文件:
Json示例:
{
"id":"0",
"meta":"down",
"type":"1",
"direction":"0",
"interval":"1800"
}
并且需要像下面这样写文件(需要匹配缩进):
id = 0
meta = down
type = 1
direction = 0
interval = 1800
现在,在转储json之后,我正在替换文本,这很好。但是我不能得到正确的压痕。下面是我的代码和输出:
def updateConfigFile(filename):
with open(filename, 'U') as f:
newText=f.read()
while ':' in newText:
newText=newText.replace(':', ' = ')
while ',' in newText:
newText=newText.replace(',', ' ')
with open(filename, "w") as f:
f.write(newText)
输出:
direction = 0
stallTimeout = 60
description = down
rampTime = 4
deepDepth = 14
deepWindow = 5
id = 1
如何获得适当的缩进?谢谢
您应该将JSON处理为JSON,而不是原始文本。特别是,您不应该依赖JSON文件的某些特殊格式
从今往后,我假设这是json文件的内容:
保存在
exampleJson.json
下您可以将json转换为格式正确的字符串,如下所示:
它生成以下字符串:
关键部分是
"%-20s= %s"
格式的字符串。%-20s
的意思是:焊盘到宽度20,左对齐希望把这个字符串保存到文件中不会有问题
相关问题 更多 >
编程相关推荐