Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between os.replace() and os.rename()?

Tags:

python

linux

I want to move a file form one directory to another in linux with python. I wish to achieve a behavior similar to bash mv command.

What is the difference in practice between the two commands

os.replace()
os.rename()

Is it simply that os.rename() will raise an error if file exists in destination while os.replace() will overwrite it?

Also if another secondary difference that I see it that the os.replace() needs a file as a destination not just the directory.

I can find a direct answer anywhere.

like image 325
KZiovas Avatar asked Dec 14 '25 18:12

KZiovas


1 Answers

On POSIX systems, the rename system call will silently replace the destination file if the user has sufficient permissions. The same is not true on Windows: a FileExistsError is always raised.

os.replace and os.rename are the same function on POSIX systems, but on Windows os.replace will call MoveFileExW with the MOVEFILE_REPLACE_EXISTING flag set to give the same effect as on POSIX systems.

If you want consistent cross-platform behaviour you should consider using os.replace throughout.

like image 197
djones Avatar answered Dec 16 '25 13:12

djones