回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>Python 3.6版</p>
<p>我有一个生成词典列表的程序。你知道吗</p>
<p>如果我打印到屏幕上:</p>
<pre><code>print(json.dumps(output_lines, indent=4, separators=(',', ': ')))
</code></pre>
<p>它完全按照我想看到的那样打印出来:</p>
<pre><code>[
{
"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
},
</code></pre>
<p>但如果我想把它打印到一个文件中:</p>
<pre><code>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)
</code></pre>
<p>文件是一行巨大的文本。你知道吗</p>
<p>我希望文件中的格式与打印到屏幕时的格式相同。你知道吗</p>
<p>我不明白为什么我会丢失格式。你知道吗</p>