Dict/Json输出文件中逐行显示
- 需要的效果如下图,我有一个list of dicts,它在json.cn中显示如下,我需要它输出到文件也显示同样的格式,而非整个list是一行:

- 方法:
import json
dataset = [{"a":1, "b":2, "c":3}, {"d":[1,2,3], "e":[2,3,4], "f":[3,4,5]}]
with open("your_file_path", "w", encoding="utf8") as wo:
json.dump(dataset, wo, ensure_ascii=False, indent=4)
...
with open("your_file_path", encoding="utf8") as ro:
dataset = json.load(ro)
- json.dump()把dataset写到wo文件流中,ensure_ascii=False确保中文字符编码正确,indent>0设置各行的相对缩进值;最后文件中的显示效果大致就如1中的图;
- 如果要读取3中文件的对象,可以直接json.load(ro),如上代码所示;