I'm quite a newbie of Python and tryed to make a program that creates a list of JSON by compiling a form thanks to tk library and write it in a .json file. But I used a bad logic and everytime I re-run the program, it does exactly what I want and write a new JSON, but it delete the old ones that were written on that file.
getdata = []
def submit():
name = name_var.get()
img = img_var.get()
description = description_var.get()
d = { "name": name, "image": img, "description": description}
getdata.append(d)
print("This is what's in the list", getdata)
name_var.set("")
img_var.set("")
description_var.set("")
with open("interest.json",'w', encoding='utf-8') as f:
json.dump(getdata,f,ensure_ascii=False, indent = 2)
The following is a part of a test I've made to try saving the already existing .json file in a python variable to check if it's empty. Not sure if it's right. I also thought that maybe I have to work with two .json files.
with open("interest.json",'r') as filetoread:
transform_json = json.loads(filetoread)
if len(transform_json) < 1:
with open("interest.json",'w', encoding='utf-8') as f:
json.dump(getdata,f,ensure_ascii=False, indent = 2)
else:
# put a condiction to keep writing on the same file if that already exist
I hope I didn't just choose the worst way to do it. Thank you for the help.