python - 如何在循环中的每次迭代中转储/写入具有不同名称的多个 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 开始的计数器?
解决方案
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'
。
推荐阅读
- reactjs - 如何使用 webpack 和 Babel 将 TypeScript/Less 文件编译成 JavaScript/CSS?
- flutter - 推荐使用 Flutter 键盘类型输入十六进制字符串?
- python - ImportError:/lib64/libc.so.6:导入 tensorflow 后未找到版本“GLIBC_2.15”
- javascript - 由于更新了animejs,我的javascript不再起作用
- reactjs - React redux 嵌套数组更新良好实践和 perfs
- javascript - 以模态显示表单的 POST 数据
- fullcalendar - FullCalendar 每周活动限制
- python-3.x - AWS SageMaker:ValueError:y 中人口最少的类只有 1 个成员错误
- r - 下标和上标的 Markdown 代码
- mongodb - mongodb - $sort 仅子文档