Making a json saving system for my python game

I made a simple counter so I can see if I can store data from one program and keep it for the next time I run it however I’m not sure how I can do that. This is what I’ve got so far. If your wondering what I’ll use this for afterword’s its for a pygame.

import json, time
start = 0
with open("data.json", "r") as read_file:
  data = json.load(read_file)
while True:
  save = data
  with open("data.json", "w") as write_file:
    json.dump(save, write_file)
  with open("data.json", "r") as read_file:
    data = json.load(read_file)
    if data=={'part': 0}:
      print("Works")
  start = start + 1
  time.sleep(1)
  print(data)
  save = data

As you may see when you run this code it doesn’t continue counting it only resets and starts again.

>Solution :

So there are a couple of issues here:

import json, time
start = 0

with open("data.json", "r") as read_file:
  data = json.load(read_file)

while True:
  save = data
# unnecessary variable assignment! you can just keep it as 'data'
  with open("data.json", "w") as write_file:
    json.dump(save, write_file)
# you're repeatedly reading and writing the data here: why not set it to just write the data if you're keeping it in memory anyway?
  with open("data.json", "r") as read_file:
    data = json.load(read_file)
    if data=={'part': 0}:
# compare values and not the whole dict object
      print("Works")
  start = start + 1
# start is now 1
  time.sleep(1)
  print(data)
  save = data

This would probably be better written out as:

game_data = { 'yourdata' : 1 }

def save_game_data(data):
    with open("data.json", "w") as write_file:
        json.dump(data, write_file)

def load_game_data():
    # check to see if data exists
    try:
        with open("data.json", "r") as read_file:
            return json.load(read_file)
    except FileNotFoundError:
        # if you can't find the file, create new game data
        return game_data

You could then use a loop to occasionally dump your data into the json file like:

import json, time

current_save = load_game_data()

while True:
    save_game_data(current_save)
    if current_save['yourdata']==1:
        print("Works")
    current_save['yourdata'] += 1
    time.sleep(1)
    print(current_save)

This loop loads either the current save or starts a new one, then uses the function to save the data for each loop. You might want to consider– do you want to save repeatedly? How long do you want between saves? Do you want people to be able to trigger a save function? Is there going to be a cost to this loop? You could consider saving the data only when it is modified or when specific conditions are met, rather than saving it on every iteration of the loop.

Leave a Reply