Search code examples
pythonjsonpi

how to make python write json read and write same file for each cicle


i'm writing a script in Python doing a while true cicle, how can I make my script take the same file abc123.json for each cicle and modify some variables in it?


Solution

  • If I understand your question correctly, you want to read a file named abc123.json somewhere on a local hard drive that is accessible via path and modify a value for a key (or more) for that json file, then re-write it. I'm pasting an example of some code I used a while ago in hopes it helps

    import json
    from collections import OrderedDict
    from os import path
    
    def change_json(file_location, data):
        with open(file_location, 'r+') as json_file:
            # I use OrderedDict to keep the same order of key/values in the source file
            json_from_file = json.load(json_file, object_pairs_hook=OrderedDict)
            for key in json_from_file:
                # make modifications here
                json_from_file[key] = data[key]
            print(json_from_file)
            # rewind to top of the file
            json_file.seek(0)
            # sort_keys keeps the same order of the dict keys to put back to the file
            json.dump(json_from_file, json_file, indent=4, sort_keys=False)
            # just in case your new data is smaller than the older
            json_file.truncate()
    
    # File name
    file_to_change = 'abc123.json'
    # File Path (if file is not in script's current working directory. Note the windows style of paths
    path_to_file = 'C:\\test'
    
    # here we build the full file path
    file_full_path = path.join(path_to_file, file_to_change)
    
    #Simple json that matches what I want to change in the file
    json_data = {'key1': 'value 1'}
    while 1:
        change_json(file_full_path, json_data)
        # let's check if we changed that value now
        with open(file_full_path, 'r') as f:
            if 'value 1' in json.load(f)['key1']:
                print('yay')
                break
            else:
                print('nay')
                # do some other stuff
    

    Observation: the code above assumes that both your file and the json_data share the same keys. If they dont, your function will need to figure out how to match keys between data structures.