Home > Back-end >  File Read/Write in Python
File Read/Write in Python

Time:07-04

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)

CodePudding user response:

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.

CodePudding user response:

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

  • Related