Skip to main content
 首页 » 编程设计

python之保存数据时保留新行

2025年05月04日12emanlee

当我尝试将此 json 数据 [1] 保存到文件中时,python 不会保留 json 数据的新行。我想保存它。我该怎么做?

[1] 保存数据的代码

data = { 
  "queuecapacity": "0.0", 
  "maps": "9", 
  "byteswritten": "44089526", 
  "time": "52.5484039783", 
  "mem": 49222464, 
  "bytesread": "1102253727", 
  "cpu": 32000 
} 
 
 with open(path, 'w') as out_file: 
    out_file.write(json.dumps(data)) 

请您参考如下方法:

将缩进选项传递给 json.dumps()

out_file.write(json.dumps(data, indent=4)) 

来自 https://docs.python.org/2/library/json.html#json.dump ,

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. None (the default) selects the most compact representation.

另外,如果您已经有了文件对象,您可以使用 json.dump() 重写您的调用,

json.dump(data, out_file, indent=4)