Why os.rename() is raising an exception in Python 2.7?

11,115

Solution 1

On Python 3.3+ you could use os.replace() instead of os.rename() to overwrite the existing file and to avoid the error on Windows.

On older Python versions you could emulate os.replace() using ctypes module:

# MOVEFILE_REPLACE_EXISTING = 0x1; MOVEFILE_WRITE_THROUGH = 0x8
ctypes.windll.kernel32.MoveFileExW(src, dst, 0x1)

See how atomicfile.atomic_rename() is implemented on Windows.

Solution 2

From the Windows system error codes list:

ERROR_ALREADY_EXISTS

183 (0xB7)

Cannot create a file when that file already exists.

You are trying to create a file that already exists. Delete it first or pick a different filename.

As a bonus tip: Use the os.path.join() function to correctly join paths:

os.path.join(dir_name, '{0}_{1}_{2}{3}'.format(f_parent, parts[0], date, extension))

I've also used string formatting to create your filename.

Share:
11,115
mat.viguier
Author by

mat.viguier

Since 8086

Updated on June 26, 2022

Comments

  • mat.viguier
    mat.viguier almost 2 years
    print(path)
    print(dir_name+"\\"+f_parent+"_"+parts[0]+"_"+date+extension)
    os.rename(path, dir_name+"\\"+f_parent+"_"+parts[0]+"_"+date+extension)
    

    Lines 1 & 2 are debug and statements and these print:

    D:\Doc\Papa\Photos\2012\2012_07_divers\CSC_3709.jpg
    D:\Doc\Papa\Photos\2012\2012_07_divers\2012_07_divers_CSC_3709_2012_07_06_21_04_26.jpg
    

    Line 3 raises:

    File "D:\Doc\Papa\scripts\python\photosort\photosort.py", line 83, in rename
      os.rename(path, dir_name+"\\"+f_parent+"_"+parts[0]+"_"+date+extension)
    WindowsError: [Error 183] Impossible de créer un fichier déjà existant
    

    which translates to:

     WindowsError: [Error 183] Can not create a file that already exists