如何在python中创建一个循环来使用来自不同列表的两个参数编写json文件

4ioopgfo  于 2023-03-04  发布在  Python
关注(0)|答案(2)|浏览(112)

我需要帮助创建类似循环的东西来缩短我的代码。目前我有:
将数据从JSON字典写入适当文件的代码:

file_01 = f'{root_path}/{output}/{file_name_01}.{json_ext}'
file_02 = f'{root_path}/{output}/{file_name_02}.{json_ext}'
file_03 = f'{root_path}/{output}/{file_name_03}.{json_ext}'
file_04 = f'{root_path}/{output}/{file_name_04}.{json_ext}'
file_05 = f'{root_path}/{output}/{file_name_05}.{json_ext}'
file_06 = f'{root_path}/{output}/{file_name_06}.{json_ext}'
file_07 = f'{root_path}/{output}/{file_name_07}.{json_ext}'

json_dic_01 = [{"test": "test", "test1" : "test1"}]
json_dic_02 = [{"test": "test", "test1" : "test1"}]
json_dic_03 = [{"test": "test", "test1" : "test1"}]
json_dic_04 = [{"test": "test", "test1" : "test1"}]
json_dic_05 = [{"test": "test", "test1" : "test1"}]
json_dic_06 = [{"test": "test", "test1" : "test1"}]
json_dic_07 = [{"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_01, file_01)
save_to_json(json_dic_02, file_02)
save_to_json(json_dic_03, file_03)
save_to_json(json_dic_04, file_04)
save_to_json(json_dic_05, file_05)
save_to_json(json_dic_06, file_06)
save_to_json(json_dic_07, file_07)

现在我想通过使用类似循环的东西来减少save_to_json()函数的迭代次数
我创建了json_dics的列表:

json_dics = [json_dic_01, json_dic_02, json_dic_03, json_dic_04, json_dic_05, json_dic_06, json_dic_07]

fnames

fnames = [file_01, file_02, file_03, file_04, file_05, file_06, file_07]

我的愿景是:

for dic in json_dics:
    take the assigned fname and save

如有任何帮助和建议,我将不胜感激。

2uluyalo

2uluyalo1#

您可以使用zip()函数来迭代两个json_dics列表,因为这会有所帮助。

json_dics = [json_dic_01, json_dic_02, json_dic_03, json_dic_04, json_dic_05, json_dic_06, json_dic_07]
fnames = [file_01, file_02, file_03, file_04, file_05, file_06, file_07]

for json_dic, fname in zip(json_dics, fnames):
    save_to_json(json_dic, fname)
1yjd4xko

1yjd4xko2#

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

编辑:您也可以为第一行创建一个循环:
假设您有列表filenames中的每个file_name_xx

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

您可以对json_dic执行相同的操作

相关问题