Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Overwrite in Os.Rename

Tags:

python

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"); 
like image 786
Splashlin Avatar asked Nov 12 '11 20:11

Splashlin


People also ask

How do I rename a file in OS?

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.

How do you overwrite a filename in Python?

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”.

How do you rename a directory in Python?

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.


2 Answers

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.

like image 128
atzz Avatar answered Sep 28 '22 05:09

atzz


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') 
like image 25
Blender Avatar answered Sep 28 '22 05:09

Blender