Home > database >  Is there anyway to update values in a JSON file after a certain interval of time?
Is there anyway to update values in a JSON file after a certain interval of time?

Time:02-14

Let's say I have a json file with multiple values as such:

{
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}

Is there any way I can update each separate value in the file after a certain interval of time? For example, I can change the Google value from 5 to 6 then 7 and so on each minute.

CodePudding user response:

With time.sleep() you can do this. time.sleep() delays your code for the amount of seconds that you specify. If you put it in a different thread, you can execute code whilst this is happening. This is some code for the threaded version, but you can remove threading by just calling updatedict()

import json
from time import sleep
import threading

values = {
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}
def updatedict():
    while True:
        global values
        #incrementing values
        for value in values:
            values[value]  = 1
        #Writing file
        with open("values.json","w ") as f:
            f.write(json.dumps(values))
        #Sleeping 1 minute
        sleep(60)
#Starting new thread
threading.Thread(target=updatedict).start()
#Any code you wish to run at the same time as the above function

If you intend to run the script multiple times each incrementing onto what is already there, replace the existing values variable assignment with

try:
    with open("values.json") as f:
        values = json.load(f)
#If the file is not found, regenerates values
except FileNotFoundError:
    values = {
    "google":5,
    "apple":4,
    "msft":3,
    "amazon":6
}
  • Related