The most naive, worst way to replace the contents of a file:
f = open('file.txt', 'w') f.write('stuff') f.close()
Obviously, if this operation fails at some point before closing, you will lose the contents of the original file, not necessarily ending with new content.
So what is the perfectly correct way to do this (if any). I imagine something like:
f = open('file.txt.tmp', 'w') f.write('stuff') f.close() move('file.txt.tmp', 'file.txt') # dangerous line?
But is it completely atomic and safe? What are the right commands to actually execute the movement. If I have another process with an open connection to file.txt , I assume that it will hold the pointer to the source file until it is closed. What if another process tries to open file.txt in the middle of a move?
I don't care what version of the file my processes have, as long as they get the full, undamaged version.
source share