Safely renaming a file without overwriting

Wolfgang Draxinger wdraxinger at darkstargames.de
Sat Oct 28 18:29:06 EDT 2006


Steven D'Aprano wrote:

> Open "the" file? There are potentially two files -- the source
> and destination. I only want to do the rename if the
> destination *doesn't* exist, so there is no destination file to
> open. How will it help me to lock the source file? Have I
> misunderstood?

I forgot to say, to open the source file with O_CREAT | O_EXCL.
The open will fail if the file already exists. By locking the
file no other process will be able to access it, but the process
that holds the lock can do with it anything. This includes to
rename an existing file to the name of the opened one - the
previously created placeholder file will get unlinked before,
but there is _probably_ no way that any process can intercept
this. It is an interesting thing, that files that are opened
remain fully usable and accessible if you unlink them as long
you don't close them. You have to close it, to remove all
remains of it.

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: hexarith at jabber.org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E



More information about the Python-list mailing list