As the title says, I wanted a python program that changes the file name, but I wanted to overwrite if there already is 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 already is file with that destination name.
os.rename<original, output>
WindowsError: [Error 183] Cannot create a file when that file already exists
What fix should I make?
This error only occurs on 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 already a file or folder on the destination, with following code:
See also this answer: https://stackoverflow.com/a/84173/955026
If the file exists, remove it first before renaming the original file. Of course you should check if you are not removing the original file (so
script.py file1 file1
should not remove file1).Please find the below approach which i followed and it is working fine
It will overwrite the existing file with new data if it already exist also.
You can use shutil.move, it will overwrite on windows:
Demo:
On Windows
os.rename
won't replace the destination file if it exists. You have to remove it first. You can catch the error and try again after removing the file: