Search code examples
pythonpython-2.7renamefile-rename

Python program to rename file names while overwriting if there already is that file


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?


Solution

  • 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:

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