0

The code below works for updating my json file but it unnecessarily opens the file twice, once to read and then to write. I tried opening it with 'r+' instead of 'r', but then it appended the revised json instead of replacing the original file. 'w+' also didn't work - the file couldn't be read.

Any thoughts or ideas for how to update without opening the file twice?

    with open(shared_file_path,'r') as json_file:
        data = json.load(json_file)
    if data[param] != value:
        data[param] = value
        with open(shared_file_path,'w') as json_file:
            json.dump(data, json_file)
2
  • I use a similar code and I've never wondered if it can be done easily... Hope someone has an answer, but I think that's how you're supposed to do it. Commented Jul 3, 2022 at 22:31
  • Nothing wrong with opening the file twice, since you're reading and then writing. Commented Jul 4, 2022 at 0:08

2 Answers 2

2

That's already a good way to do it. The "w" also deletes the existing file so that you don't have to worry about existing data when you add new stuff. If you want to do it without reopening, you could seek to the beginning and truncate the file

with open(shared_file_path,'r+') as json_file:
    data = json.load(json_file)
    if data[param] != value:
        data[param] = value
        json_file.seek(0)
        json_file.truncate()
        json.dump(data, json_file)

But opening twice is fine. Its not an expensive operation.

Sign up to request clarification or add additional context in comments.

Comments

0

You want to seek to start of file and then issue some reads.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.