-1

I have a Python script that writes some data to a file. I want to overwrite the the contents of the file with some new data.

When the file doesn't exist I create it and add data by using -

with open(path/to/myfile + '.json', 'w') as outfile:
    json.dump(mydata, outfile)

Now there is some newdata which should be written in place of mydata inside myfile.

If I understood correctly from some answers, using -

with open(path/to/myfile + '.json', 'w') as outfile:
    json.dump(newdata, outfile)

deletes myfile and creates a new one with newdata as its contents. Please correct me here if my understanding is wrong.

What I want to do is not delete the file and just overwrite the contents of the file (because I need to compare the last modified times of this file in another application). How can I do that?

EDIT: The duplicate link given answers how to append to an existing file. My objective is to overwrite the contents of the file entirely.

  • "... deletes myfile and creates a new one with newdata as its contents. Please correct me here if my understanding is wrong." This seems to be wrong. I have a file here that I created in 2018, and I just wrote to it using open() in "w" mode. The "created" date is still 3/9/2018, not 2/11/2019. – Kevin Feb 11 '19 at 14:36
  • 1
    `open` with mode `w` does not delete and create a new file. The file is truncated when opened with mode `w`. I recommend against updating files in place as the truncation of the original file can cause data loss if the new file isn't completely written. – Dan D. Feb 11 '19 at 14:38
  • @DanD, "I recommend against updating files in place as the truncation of the original file can cause data loss if the new file isn't completely written." - Can you please explain this? –  Feb 11 '19 at 14:42
  • Please show an example of writing or re-writing a file where the *modified* date does not behave as you intend. – mkrieger1 Feb 11 '19 at 14:43
  • The data loss results from the truncation destroying the prior durable copy of the past data before the current data is made durable. There is a window of time in that where the only data exists in memory and when the program is interrupted, the on disk data may only be partially written. As the past data on disk was destroyed, one can not recover by reverting to the prior data. – Dan D. Feb 11 '19 at 14:53

2 Answers2

1

The mtime of the file will be the time when json.dump was called, no matter if it is a new file or not. If your other application keeps track of the mtime, this should be enough to decidev if the file has changed.

0

Whether it deletes it or not, the modified time will change. However, I don't believe that opening with "w" deletes the file, it opens it with the file pointer at the beginning ready to write data.

Oli
  • 15
  • 5