Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Saving to Json file
#1
Hi all , I've saved the results from my menu to json. when i click on the saved file it looks like it is only saving 1 dictionary and then overwriting it the next time the programme is run and the menu has new selections.
This is the code i have written. Thanks in advance.

data = {}
data['batch_number'] = []
data['batch_number'].append({'batch_number':str(batch_number)})
with open('fruitBatches.json', 'w') as outfile:
    json.dump(data, outfile)
    i = 0
    while i < len(batch_number):
        print("list index is ", i)
        print("value is ", batch_number[i])
        i = i + 1
Reply
#2
That's the expected behavior. If you want different behavior, you should have your highest level data structure be a list instead of a dictionary, and then in order to add to the file you'll have to read its previous contents into memory, append to that, then dump it again. (You probably want to be mindful of the case of the file not existing the first time as well, when you would read it.)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Storing version of the downloaded libs using json file Rakshan 3 1,427 Mar-21-2023, 07:50 AM
Last Post: buran
Bug [for a h/w project] How to save and get back dictionary in a .json file in TinyDB. adithya_like_py 4 3,711 Feb-05-2021, 10:49 AM
Last Post: buran
  Changing the content of the table and saving the new data into another file femke_pythonquestion123 1 1,663 Sep-18-2020, 12:06 PM
Last Post: femke_pythonquestion123
  Extracting link list to json file naor 5 2,747 Sep-17-2020, 04:16 PM
Last Post: micseydel
  Saving the results from an input in a txt. file pythonenthusiast 2 2,817 Nov-28-2017, 03:52 PM
Last Post: wavic
  Saving an numpy.ndarray as .ply file in python Tina 4 17,299 Oct-11-2017, 06:08 PM
Last Post: Tina

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020