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.
2
Answers
You can refer to the answer here:
Difference between modes a, a+, w, w+, and r+ in built-in open function?
"w"
will truncate your file, you need to use"a"
open('file.json', 'a')
Using somewhat your code, you could do something along this
You open your file, and if it exist load the json inside
transform_json
as dictionnary, otherwise do nothingThen you check wether
transform_json
exist (so wether or not the file exist in the first place). If it doesn’t exist, create the file and add your value inside, otherwise, if it exist (sotransform_json
has value inside it), concattransform_json
with yourgetdata
, (to create a single dictionnary) and then dump_it inside your json file to overwrite previously existing jsonThe
try except
is in case your json file is invalid (empty file or bad json file), then you overwrite it, if that’s not the behavior you want (e.g you want to do something if the json is incorrect, do it instead ofpass
)