I wanted to automate the process of copying files (in their target folders) to their corresponding source folders (which has the same folder structure as the source) located in a different directory on computer...
I tried to use python's shutil.copytree, but that will copy all the target folders into the source folders and the Python documentation said that "The destination directory, named by dst, must not already exist" (which, in my case, break the rule). So what I wanted to do is to only copy the target files to the corresponding folder, so that the source and target files would end up staying in the same folder...Is it possible to do by using python?
Here I attached to the question a screenshot to further explain what I meant.
Thank you so much for your help! At the meantime, I'll try to do more research about it too!
Asked
Active
Viewed 933 times
2

Penny
- 1,218
- 1
- 13
- 32
-
Just copy them 1 by 1 with shutil.copyfile() – Muposat Dec 05 '15 at 03:02
-
BTW, your terminology is a little confusing: we normally copy _from_ the source _to_ the target (or destination). – PM 2Ring Dec 05 '15 at 05:46
2 Answers
2
Here's the modified version of shutil.copytree
which does not create directory (removed os.makedirs
call).
import os
from shutil import Error, WindowsError, copy2, copystat
def copytree(src, dst, symlinks=False, ignore=None):
names = os.listdir(src)
if ignore is not None:
ignored_names = ignore(src, names)
else:
ignored_names = set()
# os.makedirs(dst)
errors = []
for name in names:
if name in ignored_names:
continue
srcname = os.path.join(src, name)
dstname = os.path.join(dst, name)
try:
if symlinks and os.path.islink(srcname):
linkto = os.readlink(srcname)
os.symlink(linkto, dstname)
elif os.path.isdir(srcname):
copytree(srcname, dstname, symlinks, ignore)
else:
# Will raise a SpecialFileError for unsupported file types
copy2(srcname, dstname)
# catch the Error from the recursive copytree so that we can
# continue with other files
except Error, err:
errors.extend(err.args[0])
except EnvironmentError, why:
errors.append((srcname, dstname, str(why)))
try:
copystat(src, dst)
except OSError, why:
if WindowsError is not None and isinstance(why, WindowsError):
# Copying file access times may fail on Windows
pass
else:
errors.append((src, dst, str(why)))
if errors:
raise Error, errors
Using mock
(or unittest.mock
in Python 3.x), you can temporarily disable os.makedirs
by replacing os.makedirs
with a Mock object (See unittest.mock.patch
):
from shutil import copytree
import mock # import unittest.mock as mock in Python 3.x
with mock.patch('os.makedirs'):
copytree('PlaceB', 'PlaceA')

falsetru
- 357,413
- 63
- 732
- 636
0
I just found a rather easy way to make it happen.
We can use ditto command to merge the 2 folders together.
ditto PlaceB PlaceA

Penny
- 1,218
- 1
- 13
- 32