Python 3.6
我有一个程序正在生成一个词典列表。
如果我将其打印到屏幕上:
print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
它完全按照我想要的方式打印出来:
[
{
"runts": 0,
"giants": 0,
"throttles": 0,
"input errors": 0,
"CRC": 0,
"frame": 0,
"overrun": 0,
"ignored": 0,
"watchdog": 0,
"pause input": 0,
"input packets with dribble condition detected": 0,
"underruns": 0,
"output errors": 0,
"collisions": 0,
"interface resets": 2,
"babbles": 0,
"late collision": 0,
"deferred": 0,
"lost carrier": 0,
"no carrier": 0,
"PAUSE output": 0,
"output buffer failures": 0,
"output buffers swapped out": 0
},
{
"runts": 0,
"giants": 0,
"throttles": 0,
"input errors": 0,
"CRC": 0,
"frame": 0,
"overrun": 0,
"ignored": 0,
"watchdog": 0,
"pause input": 0,
"input packets with dribble condition detected": 0,
"underruns": 0,
"output errors": 0,
"collisions": 0,
"interface resets": 2,
"babbles": 0,
"late collision": 0,
"deferred": 0,
"lost carrier": 0,
"no carrier": 0,
"PAUSE output": 0,
"output buffer failures": 0,
"output buffers swapped out": 0
},
但是如果我尝试将其打印到一个文件:
outputfile = ("d:\\mark\\python\\Projects\\error_detect\\" + hostname)
# print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
output_lines.append(json.dumps(output_lines, indent=4, separators=(',', ': ')))
del output_lines[-1]
with open(outputfile, 'w') as f:
json.dump(output_lines, f)
该文件是一个巨大的文本行。
我希望文件中的格式与我在屏幕上打印时的格式相同。
我不明白为什么我会丢失格式。
答案 0 :(得分:1)
我认为你所需要的只是json.dump
indent
而且应该没问题:
outputfile = ("d:\\mark\\python\\Projects\\error_detect\\" + hostname)
# print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# output_lines.append(json.dumps(output_lines, indent=4, separators=(',', ': ')))
# del output_lines[-1]
with open(outputfile, 'w') as f:
json.dump(output_lines, f, indent=4, separators=(',', ': '))
格式化字符串然后在字符串上重新运行dump对我来说没有多大意义。
答案 1 :(得分:0)
尝试简单地输出格式化的json.dumps
,而不是再次通过json.dump
运行。
with open(outputfile, 'w') as f:
f.write(output_lines)
答案 2 :(得分:-1)
假设您的程序生成此词典列表
>>> list_of_dicts = [dict(zip(list(range(2)),list(range(2)))), dict(zip(list(range(2)),list(range(2))))]
>>> list_of_dicts
[{0: 0, 1: 1}, {0: 0, 1: 1}]
你能做的是
>>> import json
>>> str_object = json.dumps(list_of_dicts, indent=4)
>>> repr(str_object)
'[\n {\n "0": 0, \n "1": 1\n }, \n {\n "0": 0, \n "1": 1\n }\n]'
>>> str_object
[
{
"0": 0,
"1": 1
},
{
"0": 0,
"1": 1
}
]
现在你可以写str_object
>>> with open(outputfile, 'w') as f:
f.write(str_object)
这使得文件中的格式与将其打印到屏幕时的格式相同。