barney12 barney12 - 5 months ago 37
Python Question

Force shutil copy to continue through list when encountering missing source file

I'm using shutil to copy output from an upstream process based on user supplied files. Sometimes those files aren't compatible with the upstream process, and as such the final file I'm attempting to move won't be created.

I'm handing shutil a list of verbose file paths, I want it to continue to move all items in the list even when one or more of the source files are missing.

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)


Thank you.

Answer

One approach would be to simply add exception handling around the call, for example:

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

This would display the following for missing files:

[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'