Consider the following directory tree
Work--->subdir1--->File1
| |
| ---->File2
|
-->subdir2--->File3
There exists another similar directory tree
Gold--->subdir1--->File1
| |
| ---->File2
|
-->subdir2--->File3
I have to write a script to copy the Work directory to another location. I have been using shutil.copytree for the same.
The problem is, at times (but not always) I may not have permission to access some files, say, File2 in the Work directory, and will get the following error:
Traceback (most recent call last):
File "C:\Script.py", line 81, in <module>
shutil.copytree(source_loc,dest_loc)
File "C:\Python32\lib\shutil.py", line 239, in copytree
raise Error(errors)
shutil.Error: [('C:\\Work\\subdir1\\File2',
'C:\\Dest\\subdir1\\File2',
"[Errno 13] Permission denied: 'C:\\Work\\subdir1\\File2'")]
In such situations, I will have to copy those corresponding files from the Gold directory.
Is there a way in which I can automate the copying of the corresponding files from Gold directory through an exception? Say something like:
try:
shutil.copytree(r'C:\Work',r'C:\Dest')
except:
<< Copy Inaccessible Files from Gold >>
I was initially thinking about using os.walk, to copy files individually. This way whenever I encounter an exception for a particular file, I will be able to copy that corresponding file from Gold. Is there a better way?
You can get the list of files that failed to copy from shutil.Error. From reading the source, shutil.Error contains (src, dst, why) triplets. You can do something like: