This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: os.rename() silently overwrites files
Type: Stage:
Components: Library (Lib) Versions: Python 2.2
process
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: Nosy List: jojoworks, pje
Priority: normal Keywords:

Created on 2004-03-19 16:11 by jojoworks, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (2)
msg20272 - (view) Author: Deleted User jojoworks (jojoworks) Date: 2004-03-19 16:11
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.
msg20273 - (view) Author: PJ Eby (pje) * (Python committer) Date: 2004-03-20 21:25
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).
History
Date User Action Args
2022-04-11 14:56:03adminsetgithub: 40053
2004-03-19 16:11:36jojoworkscreate