Is it possible to force a rename os.rename to overwrite another file if it already exists? For example in the code below if the file Tests.csv already exists it would be replaced by the Tests.txt file (that was also renamed to Tests.csv).
os.rename("C:\Users\Test.txt","C:\Users\Tests.csv");
Use rename() method of an OS module Use the os. rename() method to rename a file in a folder. Pass both the old name and a new name to the os. rename(old_name, new_name) function to rename a file.
To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile. txt”.
Python os. rename() function enable us to rename a file or directory, directly from command prompt or IDE. The os. rename() function alters the name of the source/input/current directory or file to a specified/user-defined name.
Since Python 3.3, there is now a standard cross-platform solution, os.replace
:
Rename the file or directory src to dst. If dst is a directory,
OSError
will be raised. If dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement).Availability: Unix, Windows.
New in version 3.3.
However, contrary to the documentation, on Windows it's not guaranteed to be atomic (in Python 3.4.4). That's because internally it uses MoveFileEx
on Windows, which doesn't make such a guarantee.
You could try shutil.move()
:
from shutil import move move('C:\\Users\\Test.txt', 'C:\\Users\\Tests.csv')
Or os.remove
and then shutil.move
:
from os import remove from shutil import move remove('C:\\Users\\Tests.csv') move('C:\\Users\\Test.txt', 'C:\\Users\\Tests.csv')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With