Rename file without overwriting existing files

Peter Otten __peter__ at web.de
Mon Jan 30 08:58:10 EST 2017


Jussi Piitulainen wrote:

> Peter Otten writes:
> 
>> Steve D'Aprano wrote:

>>> The wider context is that I'm taking from 1 to <arbitrarily huge number>
>>> path names to existing files as arguments, and for each path name I
>>> transfer the file name part (but not the directory part) and then rename
>>> the file. For example:
>>> 
>>> foo/bar/baz/spam.txt
>>>
>>> may be renamed to:
>>>
>>> foo/bar/baz/ham.txt
>>> 
>>> but only provided ham.txt doesn't already exist.
>>
>> Google finds
>>
>> http://stackoverflow.com/questions/3222341/how-to-rename-without-race-conditions
>>
>> and from a quick test it appears to work on Linux:
> 
> It doesn't seem to be documented. 

For functions with a C equivalent a look into the man page is usually 
helpful.

> I looked at help(os.link) on Python
> 3.4 and the corresponding current library documentation on the web. I
> saw no mention of what happens when dst exists already.
> 
> Also, creating a hard link doesn't seem to work between different file
> systems, which may well be relevant to Steve's case.

In his example above he operates inside a single directory. Can one 
directory spread across multiple file systems?

> I get:
> 
>     OSError: [Errno 18] Invalid cross-device link: [snip]
> 
> And that also is not mentioned in the docs.





More information about the Python-list mailing list