Run the following code from a directory that contains a directory named bar
(containing one or more files) and a directory named baz
(also containing one or more files). Make sure there is not a directory named foo
.
import shutil
shutil.copytree('bar', 'foo')
shutil.copytree('baz', 'foo')
It will fail with:
$ python copytree_test.py
Traceback (most recent call last):
File "copytree_test.py", line 5, in <module>
shutil.copytree('baz', 'foo')
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/shutil.py", line 110, in copytree
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/os.py", line 172, in makedirs
OSError: [Errno 17] File exists: 'foo'
I want this to work the same way as if I had typed:
$ mkdir foo
$ cp bar/* foo/
$ cp baz/* foo/
Do I need to use shutil.copy()
to copy each file in baz
into foo
? (After I've already copied the contents of 'bar' into 'foo' with shutil.copytree()
?) Or is there an easier/better way?
The previous solution has some issue that
src
may overwritedst
without any notification or exception.I add a
predict_error
method to predict errors before copy.copytree
mainly base on Cyrille Pontvieux's version.Using
predict_error
to predict all errors at first is best, unless you like to see exception raised one by another when executecopytree
until fix all error.You can modify
shutil
and get the effect (on my version ofshutil
this is on line315
)Change
To
Try This:
A merge one inspired by atzz and Mital Vora:
In slight improvement on atzz's answer to the function where the above function always tries to copy the files from source to destination.
In my above implementation
I am using above function along with scons build. It helped me a lot as every time when I compile I may not need to copy entire set of files.. but only the files which are modified.
This limitation of the standard
shutil.copytree
seems arbitrary and annoying. Workaround:Note that it's not entirely consistent with the standard copytree:
symlinks
andignore
parameters for the root directory of thesrc
tree;shutil.Error
for errors at the root level ofsrc
;shutil.Error
for that subtree instead of trying to copy other subtrees and raising single combinedshutil.Error
.