0

I have configuration file that contain list of some other configuration files, all saved into .json.
The problem is, then I try to delete one of configuration files from list (because they are not more needed) I can't use lsit.remove and del.

.json file:

{
  "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"
  ]
}

code I am using to do that:

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!")
  • Ok, maybe the real problem here is that you try to use `i` as index, but `i` is a `dict`. Anyway, seperating the search loop from the deletion is always a good idea. – H. Doebler Aug 18 '21 at 13:31
  • Does this answer your question? [How to remove items from a list while iterating?](https://stackoverflow.com/questions/1207406/how-to-remove-items-from-a-list-while-iterating) – JonSG Aug 18 '21 at 13:35

1 Answers1

0

You cannot delete a list item while iterating over the list. Use the loop to find the index of the item to remove, then remove afterwards. Something like

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
H. Doebler
  • 633
  • 4
  • 9