Skip to content Skip to sidebar Skip to footer

Why Os.rename() Is Raising An Exception In Python 2.7?

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 sta

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.

Solution 3:

The name you are trying to use already belongs to something. Ie, there is already a file called:

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

Add a check to your function

Post a Comment for "Why Os.rename() Is Raising An Exception In Python 2.7?"