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)
文件是一行巨大的文本。你知道吗
我希望文件中的格式与打印到屏幕时的格式相同。你知道吗
我不明白为什么我会丢失格式。你知道吗
假设你的程序生成了这个字典列表
你能做的就是
现在你可以写
str_object
这使得文件中的格式与您在屏幕上打印时的格式相同。你知道吗
试着简单地输出格式化的
json.dumps
,而不是再次通过json.dump
运行它。你知道吗我想你所需要的就是
json.dump
和indent
的配合,应该可以:格式化为字符串,然后在字符串上重新运行dump对我来说没有多大意义。你知道吗
相关问题 更多 >
编程相关推荐