python如何基于word添加适当的缩进
我正在将json文件写入键值属性文件: Json示例:python如何基于word添加适当的缩进,python,Python,我正在将json文件写入键值属性文件: Json示例: { "id":"0", "meta":"down", "type":"1", "direction":"0", "interval":"1800" } 并且需要像Belowned一样写入文件以匹配缩进: id = 0 meta = down type = 1 direction = 0
{
"id":"0",
"meta":"down",
"type":"1",
"direction":"0",
"interval":"1800"
}
并且需要像Belowned一样写入文件以匹配缩进:
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文件的内容:
{"id":"0", "meta": "down", "type": "1", "direction": "0", "interval":"1800"}
保存在exampleJson.json下
您可以将json转换为格式正确的字符串,如下所示:
import json
def configFileToString(filename):
with open(filename, 'r') as f:
j = json.load(f)
return "\n".join(["%-20s= %s" % (k, j[k]) for k in j])
print(configFileToString("exampleJson.json"))
它生成以下字符串:
id = 0
meta = down
type = 1
direction = 0
interval = 1800
关键部分是%-20s=%s格式字符串。-20s表示:焊盘宽度为20,左对齐
我希望将此字符串保存到文件中不会有问题。这不是JSON.true,让我更正它。可能会重复使用类似{:printf'{k.ljust19}={v}“,file=output\u handle在使用Python 3.6时也可以使用。@Blender感谢您的提示!或者更确切地说,有两个提示:f'…'和str.ljust是自3.6以来被认为更具Python风格的f'…'-语法,因此我应该更新答案,或者我可以保持原样,以便解决方案可以与较旧的Python版本一起使用吗?;我实际上怀疑是因为.ljust是一个单独的方法调用,更接近C-sprintf-version实际上可能会快一点,不是吗?@Andreytukin:f-strings在本例中比%-格式快约18倍,比新型字符串格式快约30倍,但我之所以建议它,只是因为我永远记不住%-格式语法。