Issue 919605: os.rename() silently overwrites files (original) (raw)
Python 2.2.2 from Mandrake GNU/Linux 9.0
os.rename() should throw an exception when the program tries to rename file to an existing filename. Such a situation is namely usually caused by a bug in the calling program. The current behavior (silently replacing old file content with the new one) is dangerous to programmer's data.
If the program wants to overwrite files, it can use
try: os.rename(old,new) except IOError: os.unlink(new) os.rename(old,new)
or something similar to do so.
Logged In: YES user_id=56214
This behavior is as documented. See:
http://www.python.org/doc/2.2/lib/os-file-dir.html
under 'rename' for details.
Note that 'os.rename' is specifically intended to expose the underlying platform's rename behavior. On Unix-like operating systems, this means overwriting the destination, if present.
Unfortunately, neither Unix nor Windows can safely emulate the other OS's behavior here, without causing potential race conditions in a multi-user or multi-process environment. Note, for instance, that your example code does not correctly emulate os.rename()'s current Unix behavior, because other processes could change the filesystem state between the various lines of code.
Thus, Python chooses to expose the underlying OS' semantics, rather than trying to provide a "one-size-fits-all" behavior which may not be what you want. For example, in most applications that I write, I would rather be able to have the behavior that you are objecting to, because it allows atomic modifications to files. But, Windows does not support this, which means I must use a different approach there. In the same way, Unix does not support Windows' approach (disallowing overwrite).