Skip to content
Advertisement

Adding and saving to list in external json file

I’m very new to Python and I’m struggling when it comes to saving the data that the user has entered to a json file when quitting the application. Also every time I run my code all the data inside the json file is wiped. When I enter the input to save and exit I get this error code:

JavaScript

Here is my code below:

JavaScript

I store the json file in the same directory and all it contains is a list:

JavaScript

If anyone could help me out and let me know what I’m doing wrong or any simpler method I could use, it would be greatly appreciated. Thanks

Advertisement

Answer

Your code has several issues, including the one you’re asking about.

The main thing is the overall structure: your code keeps calling functions from functions, never really returning – that can work for a very long time, but in the end it will fail, and it’s not the correct way to go about this.

Take for example your main_menu() – once an option is selected, you call the function matching it, and when the work there is done, you call main_menu() again. However, a better way to do the same:

JavaScript

This way, the menu will keep getting printed when you return to it, but every function that is executed, is allowed to return and then the loop restarts, unless option 4 was entered. And since you can allow the functions to return, no need to call main_menu() at the end of them.

Your save() function has some issues: it doesn’t need quit() any more, but you also didn’t do anything with the file you opened. A nice way to do this in Python is to use a ‘context manager’, which boils down to using with, like this:

JavaScript

That’s assuming your loaded_patients always contains all the current patients of course. Given that’s what it is for, you should consider just calling it patients.

Your file only contains a list, because a list is what you are creating in those functions and a list is a valid content for a json file. If you expected a dictionary, you should construct one in the rest of the code, but from your example it’s unclear what exactly you would expect that dictionary to look like.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement