The delete and rename operations are performed by the operating system and are atomic (on most operating systems), so no locking is required.
To write a string to file, it would be simpler to write to a temporary file first (e.g. foo.tmp) and then rename it once it is ready.