要把一个目录下的一些文件移到另一个目录,要提取的文件名在 file_names
这个List
内,而 file_dirs
则是一个存储着文件名:文件地址的 dict
,导入shutil
来操作:
for name in file_names:
try:
shutil.move(file_dirs[name], dst)
except KeyError:
continue
整体上工作的很好,只是 file_names
存在一些重复的文件名,遇到重名的就会触发Error
:
~\Anaconda3\lib\shutil.py in move(src, dst, copy_function)
559 real_dst = os.path.join(dst, _basename(src))
560 if os.path.exists(real_dst):
--> 561 raise Error("Destination path '%s' already exists" % real_dst)
562 try:
563 os.rename(src, real_dst)
Error: Destination path 'D:/***/1331430.jpg' already exists
一开始,我以为直接将Error
放到 cxcept
内处理就行,结果遇到重复的还是会触发这个Error
:
for name in file_names:
try:
shutil.move(file_dirs[name], dst)
except KeyError:
continue
except Error:
continue
于是打开 shutil.py
,发现引发的这个 Error
是shutil
模块继承OSError
后自定义的一个错误,所以更改代码如下:
for name in file_names:
try:
shutil.move(file_dirs[name], dst)
except KeyError:
continue
except OSError:
continue
结果还是不行,仍然会触发Error
,请问我该如何捕获这个错误?
既然这个 Error 是 shutil 包里面的,当然是
except shutil.Error
了