You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python循环从双列表取参数生成并写入JSON文件

用For循环批量生成JSON文件的代码改造方案

核心需求

  • 生成待写入文件的路径列表fnames = []
  • 生成对应JSON字典列表json_dics = []
  • 通过for循环调用save_to_json()函数,将每个JSON字典写入对应路径的文件

当前单文件实现方式

文件路径定义

file_xx = f'{root_path}/{output}/{file_name_xx}.{json_ext}'

JSON字典定义

json_dic_xx = [{"test": "test", "test1" : "test1"}]

写入文件函数及调用

def save_to_json(json_dic, data_to_save):
    with open(data_to_save, 'w', encoding= utf_8) as json_file:
        json.dump(json_dic, json_file, ensure_ascii= False, indent=4, sort_keys= True)

save_to_json(json_dic_xx, file_xx)

改造后的批量实现方案(经Rubén Pérez修正)

output_file_names = ['filename01', 'filename02', 'filename03']

fnames = []
for fname in output_file_names:
    fnames.append(f'{root_path}/{output}/{fname}.{json_ext}')

json_dics = [[] for _ in range(len(fnames))]

for i in range(len(fnames)):
    save_to_json(json_dics[i], fnames[i])

内容的提问来源于stack exchange,提问作者Kubix

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:00:01