Issue
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)
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.