A
A
Andrew2022-01-11 14:04:22
Python
Andrew, 2022-01-11 14:04:22

How to save in json correctly?

I have a dict of this format:

main_dict = {}
main_dict["key_1"] = "valie_1"
main_dict["key_2"] = "valie_2"

I save it to a json file in the following way:

with open("PATCHS/my_dicts.json", "a", encoding="utf-8") as file:
    json.dump(main_dict, file)

It saves one record, but when adding another record (of the same format only with different data, main_dict is generated cyclically (for)), the file does not open ... As I understand it, you need to somehow make a list of dictionaries and then add it to the file. How to implement it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2022-01-11
@bacon

You can’t just add another part of json to the data file, you must first read this data from it, update it, and at the end completely overwrite this file with updated data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question