【发布时间】:2023-03-09 20:39:01
【问题描述】:
我有一个配置文件,其中包含一些其他配置文件的列表,全部保存在 .json 中。
问题是,然后我尝试从列表中删除一个配置文件(因为不再需要它们)我不能使用 lsit.remove 和 del。
.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!")
【问题讨论】:
-
好吧,也许这里真正的问题是您尝试使用
i作为索引,但i是dict。无论如何,将搜索循环与删除分开总是一个好主意。
标签: python json python-3.x list dictionary