【问题标题】:How to dump/write multiple json files with a different name at each iteration in the loop ? e.g. +1?如何在循环中的每次迭代中转储/写入具有不同名称的多个 json 文件?例如+1?
【发布时间】: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 开始的计数器?

【问题讨论】:

    标签: python json loops file


    【解决方案1】:
    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'

    【讨论】:

    • 也许会提到这仅适用于 Python 3,因为您使用的是格式字符串?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多