Behaviour of os.rename()

Rhodri James rhodri at wildebst.demon.co.uk
Wed Mar 11 19:59:00 EDT 2009


On Wed, 11 Mar 2009 14:35:01 -0000, venutaurus539 at gmail.com  
<venutaurus539 at gmail.com> wrote:

> On Mar 11, 7:20 pm, Tim Golden <m... at timgolden.me.uk> wrote:
>> venutaurus... at gmail.com wrote:
>> > Hello all,
>> >             I got a suspicion on the behaviour of os.rename
>> > (src,dst).If the src is the path of a file and dst is a new filename
>> > this os.rename() function is infact creating a new file with the dst
>> > name in the current working directory and leaving the src as it is. Is
>> > this the expected behavior?

Yes, though part of this is Windows being bloody-minded.  It is always the  
case that if you don't give a rooted pathname (one starting with r"\") to  
pretty much any built-in function expecting a filename (in pretty much any  
language, come to that), the pathname will be assumed to be relative to  
the current working directory.  Windows complicates this by having a  
current drive too, and per-drive working directories to go with them, so  
"file.txt", "D:file.txt", r"\path\to\file.txt" and r"D:\path\to\file.txt"  
could well all be different files in different places.

>> > If i want the actual source file in its
>> > orignal location to be renamed without doing os.chdir() to that
>> > directory, is that possible?

Yes.  Give the full pathname, with drive letters and everything.

>> os.rename on windows calls the Windows MoveFile API:
>>
>>  http://msdn.microsoft.com/en-us/library/aa365239(VS.85).aspx
>>
>> Have a look at the details on that page to see what
>> the limitations / actions are. But remember -- as I've
>> indicated elsewhere -- to use the ur"\\?\c:\..." form
>> of the file names.
>>
>> And let us know if that works :)
>
> That actually was an illustration. As you've told in another chain, it
> isn't working even after appending "\\?\"

Tim's point was that you should read the MS documentation.  To be fair it  
doesn't mention doing a copy and (failing to) delete instead of moving the  
file when doing cross-volume renames, but that's what the OS will have to  
do.

-- 
Rhodri James *-* Wildebeeste Herder to the Masses



More information about the Python-list mailing list