为什么os.rename()在Python 2.7中引发异常? [英] Why os.rename() is raising an exception in Python 2.7?
本文介绍了为什么os.rename()在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)
1& 2是调试和语句和这些打印:
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
第三行提出:
文件D:\Doc\Papa\ (path \\ dir_name +\\+ f_parent +_+ parts [0] +_),重命名为
os.rename(path \python\photosort\photosort.py + date + extension)
WindowsError:[Error 183]不可能的>转换为:
WindowsError:[错误183]无法创建已存在的文件
$在Python 3.3+上,你可以使用
python.org/dev/library/os#os.replacerel =nofollow> os.replace()而不是os.rename()被覆盖现在的文件,并避免在Windows上的错误。
在旧的Python版本,你可以模拟 os.replace()
使用ctypes模块:
#MOVEFILE_REPLACE_EXISTING = 0x1; MOVEFILE_WRITE_THROUGH = 0x8
ctypes.windll.kernel32.MoveFileExW(src,dst,0x1)
了解如何 atomicfile.atomic_rename() code>
在Windows上实现。
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
解决方案
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.
这篇关于为什么os.rename()在Python 2.7中引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文