【发布时间】:2021-11-01 22:09:57
【问题描述】:
对于我在循环中创建和转储的每个 json 文件,我怎样才能使其写入新文件?
我的代码:(for循环的内容无关紧要,只是为了概述我在做什么)。
with open('my_json.json') as file:
config = json.load(file)
for pr in path_recording:
for pj in my_list[:5]:
config['input']['files'][0]['path'] = pr ## change the json file as desired
config['input']['files'][1]['path'] = pj
with open('config.json', "w") as outfile: ## create at each loop a new json dump with new name
json.dump(config, outfile)
当前输出: 1 个名为 config 的 json 文件,在循环的最后一次迭代中创建。
config.json
期望的输出: 写入文件,文件名中带有 +1 表示每次迭代。
config0.json
config1.json
config2.json
config3.json
config4.json
想法:将文件名转换为 f-string 并在其中包含一个从 0 开始的计数器?
【问题讨论】: