Is it safe to kill the Python process when writing to a file?

Question:

When opening a file for writing, is there any point in time where the file contents would be erased if the process was killed?

Here is the code used:

with open("file.txt", "r") as f:
    data = f.read()

data = modify(data)

with open("file.txt", "w") as f:
    f.write(data)
Asked By: WanderingCoder

||

Answers:

It’s unsafe. Kill the process between the open("file.txt", "w") and the point stuff starts getting written, and the file will be empty. Kill it while data is getting written, and the file can end up in a half-written state.

Programs that need to be safe about this kind of thing do it by writing output data to a new file, and then replacing the original file with the new file once the data has been fully written and flushed.

Answered By: user2357112
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.