Jan-18-2023, 08:25 PM
(This post was last modified: Jan-18-2023, 08:25 PM by deanhystad.)
In your earlier post you said this worked:
The json.load() call reads the dictionary and creates python objects. No need to call read() to get the file contents.
In addition to using json.load(file_obj) instead of json.loads(str_obj), my example used a context manager to automatically close the json file when we were done using it. Your program never closed the file. Leaving files open is a bad practice, and using a context manager makes it really easy to make sure you always close files.
f = open ('personal.json', "r") data = json.loads(f.read())This code reads the entire file and returns a str object. Then it loads() the str object to create python objects. That works, but why read the file and then convert when you can do it with one call.
python]f = open ('personal.json', "r") data = json.load(f)[/python]
The json.load() call reads the dictionary and creates python objects. No need to call read() to get the file contents.
In addition to using json.load(file_obj) instead of json.loads(str_obj), my example used a context manager to automatically close the json file when we were done using it. Your program never closed the file. Leaving files open is a bad practice, and using a context manager makes it really easy to make sure you always close files.
with open('personal.json', 'r') as file: # opens the file for reading data = json.load(file) # reads the json file and returns python obects # Automatically closes the file when you exit the code block (de-indent)
Quote:Now I have another question, I have some entries to be able to modify the data obtained from the treeview. These work and when I modify them in the tree they are updated, but how would I call the json in this situation to update the values and not to add them as another object in the list?You use json.dump(python_object) to write a json file. You cannot dump() a TreeView, so you'll need to collect the TreeView items in Python object that can be dumped. Using something that has the same structure as the object returned by json.load() would be a good idea. Maybe you can use the same object?