您可以使用json库中的dumps函数来将Python对象转换为JSON格式的字符串。在dumps函数中,您可以使用参数indent来指定缩进的空格数。例如,将indent设置为4将在每个','后进行换行操作。

下面是如何将data对象写入JSON文件并进行换行操作的示例代码:

import json

data = { "description": "The dataset of the competition", "labels": { "0": "background", "1": "liver", "2": "spleen", "3": "left kidney", "4": "right kidney" }, "modality": {"0": "CT"}, "name": "dataset", "numTraining": int(file_count0.8), "numValidation": int(file_count0.1), "numTest": int(file_count*0.1), "training": training, "validation": validation, "test": test }

将data对象转换为JSON格式的字符串,并进行换行操作

json_str = json.dumps(data, indent=4)

将JSON格式的字符串写入文件

with open("data.json", "w") as json_file: json_file.write(json_str)

将如下写入JSON文件时候如何在每个后进行换行操作:data = description The dataset of the competition labels 0 background 1 liver 2 spleen 3 left kidney 4 right kidney modality 0 CT name dataset numTraining

原文地址: https://www.cveoy.top/t/topic/izkO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录