If the file already exists, I want to overwrite it. If it doesn't exist, I want to create it and write to it. I'd prefer to not have to use a 3rd party library like lockfile (which seems to handle all types of locking.)
My initial idea was to:
In POSIX, a successful call to rename is guaranteed to have been atomic from the point of view of the current host (i.e., another program would only see the file with the old name or the file with the new name, not both or neither of them).
aspx you'll see that ReplaceFile is a complicated merge operation, with no indication that it's atomic.
mv is most definitely not atomic when the move that it performs is from one filesystem to another, or when a remote filesystem cannot implement the mv operation locally. In these instances mv could be said to be implemented by the equivalent of a cp followed by rm .
os.Rename
calls syscall.Rename
which for Linux/UNIXs uses the rename syscall (which is atomic*). On Windows syscall.Rename
calls MoveFileW
which assuming the source and destination are on the same device (which can be arranged) and the filesystem is NTFS (which is often the case) is atomic*.
I would take care to make sure the source and destination are on the same device so the Linux rename does not fail, and the Windows rename is actually atomic. As Dave C mentions above creating your temporary file (usually using ioutil.TempFile
) in the same directory as existing file is the way to go; this is how I do my atomic renames.
This works for me in my use case which is:
In the above use case simply using os.Rename
has worked perfectly well for me.
Some further reading:
*Note: I do want to point out that when people talk about atomic filesystem file operations, from an application perspective, they usually mean the operation happens or does not happen (which journaling can help with) from the users perspective. If you are using atomic in the sense of an atomic memory operation, very few filesystem operations (outside of direct I/O [O_DIRECT] one block writes and reads with disk buffering disabled) can be considered truly atomic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With