Skip to content
Advertisement

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

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)

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement