问题
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
回答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.
回答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.
回答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
来源:https://stackoverflow.com/questions/13025313/why-os-rename-is-raising-an-exception-in-python-2-7