Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python code opening json file – more optimal

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)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading