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?
Here is my version of the same task::
This is inspired from the original best answer provided by atzz, I just added replace file / folder logic. So it doesn't actually merge, but deletes the existing file/ folder and copies the new one:
Uncomment the rmtree to make it a move function.
Here is my pass at the problem. I modified the source code for copytree to keep the original functionality, but now no error occurs when the directory already exists. I also changed it so it doesn't overwrite existing files but rather keeps both copies, one with a modified name, since this was important for my application.
i would assume fastest and simplest way would be have python call the system commands...
example..
Tar and gzip up the directory.... unzip and untar the directory in the desired place.
yah?
Here is a version inspired by this thread that more closely mimics
distutils.file_util.copy_file
.updateonly
is a bool if True, will only copy files with modified dates newer than existing files indst
unless listed inforceupdate
which will copy regardless.ignore
andforceupdate
expect lists of filenames or folder/filenames relative tosrc
and accept Unix-style wildcards similar toglob
orfnmatch
.The function returns a list of files copied (or would be copied if
dryrun
if True).Here's a solution that's part of the standard library.
See this similar question.
Copy directory contents into a directory with python