Python to rename file names when overwriting if this file already exists

As the name says, I need a python program that changes the file name, but I would like to overwrite if there is already a file with that destination name.

import os, sys original = sys.argv[1] output = sys.argv[2] os.rename(original, output) 

But my code just shows me this error when there is already a file with this destination name.

  os.rename<original, output> WindowsError: [Error 183] Cannot create a file when that file already exists 

What correction should I make?

+13
python rename file-rename
source share
4 answers

On Windows os.rename , the destination file will not be replaced if it exists. You must delete it first. You can catch the error and try again after deleting the file:

 import os original = sys.argv[1] output = sys.argv[2] try: os.rename(original, output) except WindowsError: os.remove(output) os.rename(original, output) 
+12
source share

You can use shutil.move , it will be overwritten on windows:

 from shutil import move move(src,dest) 

Demo version:

 In [10]: ls Directory of C:\Users\padraic\Desktop 11/05/2015 20:20 <DIR> . 11/05/2015 20:20 <DIR> .. 11/05/2015 20:20 0 bar.txt 11/05/2015 20:20 0 foo.txt 2 File(s) 0 bytes 2 Dir(s) 47,405,617,152 bytes free In [11]: shutil.move("bar.txt","foo.txt") In [12]: ls Directory of C:\Users\padraic\Desktop 11/05/2015 20:20 <DIR> . 11/05/2015 20:20 <DIR> .. 11/05/2015 20:20 0 foo.txt 1 File(s) 0 bytes 2 Dir(s) 47,405,613,056 bytes free In [13]: shutil.move("foo.txt","bar.txt") In [14]: ls Volume in drive C has no label. Volume Serial Number is 3C67-52B9 Directory of C:\Users\padraic\Desktop 11/05/2015 20:24 <DIR> . 11/05/2015 20:24 <DIR> .. 11/05/2015 20:20 0 bar.txt 1 File(s) 0 bytes 2 Dir(s) 47,405,568,000 bytes free 
+5
source share

This error only occurs in windows, as you can find in the python documentation ( https://docs.python.org/2/library/os.html#os.rename )

You should check if there is a file or folder in the folder with the following code:

 import os.path os.path.exists(destination) 

See also this answer: fooobar.com/questions/125 / ...

If the file exists, first delete it before renaming the original file. Of course, you should check if you are not deleting the original file (therefore script.py file1 file1 should not delete file1).

0
source share

Please find the next approach that I followed and it works fine

 source_file_name = 'Test.xlsx' dst_file_name = "FinalName.xlsx" source_file_path = "presentdirectory" #os.getcwd() dst_file_path = "Destination_Folderpath" shutil.copy(os.path.join(source_file_path, source_file_name), os.path.join(dst_file_path, dst_file_name)) 

It will replace the existing file with new data if it already exists.

0
source share

All Articles