Home > Blockchain >  Python code opening json file - more optimal
Python code opening json file - more optimal

Time:02-25

How could I write this piece of code more optimal, not to have repetition? So, first I'm checking if there's a .json file, if there isn't I make it. If there is, I first open it, update it with new data, and then write in it again.

    if not os.path.exists(json_path):
        with open(json_path, "w") as json_file:
            json.dump(my_dict, json_file)
    else:
        with open(json_path) as json_file:
            data = json.load(json_file)
            data.update(my_dict)
            with open(json_path, 'w') as json__file:
                json.dump(data, json__file)

CodePudding user response:

I think you can invert your condition to read the file first. Then later write to the file because you always end up writing.

if os.path.exists(json_path):
    with open(json_path) as json_file:
        data = json.load(json_file)
    data.update(my_dict)
    my_dict = data

with open(json_path, "w") as json_file:
    json.dump(my_dict, json_file)
  • Related