遇到丢失的源文件时强制 shutil 复制继续通过列表
Force shutil copy to continue through list when encountering missing source file
我正在使用 shutil 根据用户提供的文件从上游进程复制输出。有时这些文件与上游进程不兼容,因此不会创建我尝试移动的最终文件。
我正在向 shutil 提交一份详细文件路径列表,我希望它继续移动列表中的所有项目,即使一个或多个源文件丢失。
source = ['/home/Desktop/folder/subfolder/file.ext', '/home/Desktop/folder/subfolder2/file2.ext', '/home/Desktop/folder/subfolder3/file3.ext']
dest = ['/home/Desktop/target/file.ext','/home/Desktop/target/file2.ext', '/home/Desktop/target/file3.ext']
for sou, des in zip(source, dest):
shutil.copyfile(sou, des)
一种方法是简单地在调用周围添加异常处理,例如:
import shutil
source = ['/home/Desktop/folder/subfolder/file.ext', '/home/Desktop/folder/subfolder2/file2.ext', '/home/Desktop/folder/subfolder3/file3.ext']
dest = ['/home/Desktop/target/file.ext','/home/Desktop/target/file2.ext', '/home/Desktop/target/file3.ext']
for sou, des in zip(source, dest):
try:
shutil.copyfile(sou, des)
except IOError as e:
print e
这将针对丢失的文件显示以下内容:
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder/file.ext'
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder2/file2.ext'
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder3/file3.ext'
我正在使用 shutil 根据用户提供的文件从上游进程复制输出。有时这些文件与上游进程不兼容,因此不会创建我尝试移动的最终文件。
我正在向 shutil 提交一份详细文件路径列表,我希望它继续移动列表中的所有项目,即使一个或多个源文件丢失。
source = ['/home/Desktop/folder/subfolder/file.ext', '/home/Desktop/folder/subfolder2/file2.ext', '/home/Desktop/folder/subfolder3/file3.ext']
dest = ['/home/Desktop/target/file.ext','/home/Desktop/target/file2.ext', '/home/Desktop/target/file3.ext']
for sou, des in zip(source, dest):
shutil.copyfile(sou, des)
一种方法是简单地在调用周围添加异常处理,例如:
import shutil
source = ['/home/Desktop/folder/subfolder/file.ext', '/home/Desktop/folder/subfolder2/file2.ext', '/home/Desktop/folder/subfolder3/file3.ext']
dest = ['/home/Desktop/target/file.ext','/home/Desktop/target/file2.ext', '/home/Desktop/target/file3.ext']
for sou, des in zip(source, dest):
try:
shutil.copyfile(sou, des)
except IOError as e:
print e
这将针对丢失的文件显示以下内容:
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder/file.ext'
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder2/file2.ext'
[Errno 2] No such file or directory: '/home/Desktop/folder/subfolder3/file3.ext'