首页 > 解决方案 > 如何在循环中的每次迭代中转储/写入具有不同名称的多个 json 文件?例如+1?

问题描述

对于我在循环中创建和转储的每个 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 字符串并在其中包含一个从 0 开始的计数器?

标签: pythonjsonloopsfile

解决方案


i = 0
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(f'config{i}.json', "w") as outfile:  ## create at each loop a new json dump with new name
            json.dump(config, outfile)
        i += 1

这使用了在 python 3.6 中引入的 f 字符串。'config{}.json'.format(i)如果您使用的是早期版本,您可能需要使用'config%d.json' % i'config' + str(i) + '.json'


推荐阅读