Python在列表中删除字典



我有一个包含一些其他配置文件列表的配置文件,全部保存到。json中。
问题是,然后我尝试从列表中删除一个配置文件(因为它们不再需要),我不能使用列表。删除和删除

。json文件:

{
"version": "0.1",
"trackers": [
{
"name": "some_sorter",
"file_name": "C:/Users/c1v/Desktop/some_folder/fs_data/some_tracker_conf.json",
"parent_folder": "C:/Users/c1v/Desktop/some_folder"
},
{ # this is the dict I am trying to delete
"name": "main_sort",
"file_name": "main_sort.json",
"parent_folder": "C:/Users/c1v/Desktop/main_folder_hehe"
}
],
"track_auto_run": [
"example_name_of_tracker_conf_to_run_on_program_deploy.json",
"second_one.json"
]
}

我使用的代码:

import shutil
import os
index = load_json("fs_data/index.json", "r")  # Load json and return it as dict
# shell[1] is equal to "main_sort"
not_found = True
for i in index['trackers']:
if i['name'] == shell[1]:
print(f"Found! {i}")
not_found = False
for f in os.listdir(i['parent_folder']):
shutil.rmtree(os.path.join(i['parent_folder'], f))
del index['trackers'][i]  # HERE is the problem
save_json("fs_data/index.json", index, "w", indent=2)  # save dict to json. Args: file localizatin, data to save, mode to use (I know it's kinda pointless, but sometimes I need that for debuging, indent thet will be in file)
break
if not_found:
print("Failed to found!")

在遍历列表时不能删除列表项。使用循环查找要删除的项的索引,然后再删除。就像

import shutil
import os
index = load_json("fs_data/index.json", "r")  # Load json and return it as dict
# shell[1] is equal to "main_sort"
i_remove = -1
for j, i in enumerate(index['trackers']):
if i['name'] == shell[1]:
i_remove = j
print(f"Found! {i}")
break
else:
print("Failed to found!")
if i_remove >= 0:
i = index['trackers'][i_remove]
for f in os.listdir(i['parent_folder']):
shutil.rmtree(os.path.join(i['parent_folder'], f))
del index['trackers'][i_remove]  # HERE is no problem
save_json("fs_data/index.json", index, "w", indent=2)  # save

最新更新