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

六眼飞鱼酱① 提交于 2020-01-24 09:36:46

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!