如何用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
相关产品推荐
相关产品推荐

