os independent rename

L

Lee Harr

I just got a bug report the heart of which is the
difference between unix and windows in using
os.rename

(ie, "On Windows, if dst already exists, OSError will be raised")

Hmm, I thought, maybe I'm supposed to use
shutil here. That is the "high-level" operations.
Unfortunately, shutil.move says it depends on
os.rename

So, what is the best way to do this that will
behave the same across operating systems?
 
N

Nobody

So, what is the best way to do this that will
behave the same across operating systems?

Delete the destination first, but after checking that it isn't the same as
the source.

On Windows, that last bit is harder than it seems. A string-based
comparison won't work. Even if you ignore case, there's the issue of 8.3
filenames, and some other odd cases.
 
C

Cameron Simpson

| On Sat, 17 Sep 2011 20:28:32 +0430, Lee Harr wrote:
| > So, what is the best way to do this that will
| > behave the same across operating systems?
|
| Delete the destination first, but after checking that it isn't the same as
| the source.

This is usually a step that the UNIX os.rename is designed to avoid.
By deleting first, there is a window where the destination doesn't exist
at all. Also, if the subsequent rename fails, the destination is missing
long term. os.rename() on UNIX specifies that after the call either the
new items is at destination (success) or the old item is (failure).
Either way you still have a valid destination object.

So you're breaking the model that os.rename() strives explicitly to
provide.

Cheers,
--
Cameron Simpson <[email protected]> DoD#743
http://www.cskk.ezoshosting.com/cs/

Q: How many user support people does it take to change a light bulb?
A: We have an exact copy of the light bulb here and it seems to be
working fine. Can you tell me what kind of system you have?
 
D

Dave Angel

Delete the destination first, but after checking that it isn't the same as
the source.

On Windows, that last bit is harder than it seems. A string-based
comparison won't work. Even if you ignore case, there's the issue of 8.3
filenames, and some other odd cases.
Or rename it twice, with the intermediate file being something that does
not exist. For example, generate a random name, and if it exists,
repeat till you come up with one that does not. Once the first rename
has succeeded, you can safely delete the destination.

Even this approach can have problems in the face of symlinks or multiple
partitions.

DaveA
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top