Reputation: 454
I am trying to implement a DIR-COPY. my input is like this..
source = D/Test/Source
Target = D/Test/Target
Ignore_Pattern = '*.exe'
Exclude_Sub_Folder = D/Test/Source/Backup,D/Test/Source/Backup2
I am able ignore .exe files using ignore property in copytree Did like this
shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern))
I am not sure how to exclude some of the subfolders in the source directory.
Please help.....
Thanks
Upvotes: 6
Views: 8480
Reputation: 1793
better use platform independent PurePath. Paths = [".gitkeep","app/build"]
def callbackIgnore(paths):
""" callback for shutil.copytree """
def ignoref(directory, contents):
arr = []
for f in contents:
for p in paths:
if (pathlib.PurePath(directory, f).match(p)):
arr.append(f)
return arr
return ignoref
Upvotes: 0
Reputation: 76194
You can ignore all folders that have a name of Backup or Backup2:
shutil.copytree(source , Target ,ignore=shutil.ignore_patterns(Ignore_Pattern, "Backup", "Backup2"))
"But I have multiple folders named 'Backup' and I specifically want to ignore only the one in the Test/Source directory", you say. In that case, you need to provide a custom ignoring function that investigates the full path.
to_exclude = ["D:/Test/Source/Backup", "D:/Test/Source/Backup2"]
#ignores excluded directories and .exe files
def get_ignored(path, filenames):
ret = []
for filename in filenames:
if os.path.join(path, filename) in to_exclude:
ret.append(filename)
elif filename.endswith(".exe"):
ret.append(filename)
return ret
shutil.copytree(source , Target ,ignore=get_ignored)
(Take care in to_exclude
to use the correct path separator for your particular OS. You don't want "Test\Source\Backup" getting included because you used the wrong kind of slash.)
Upvotes: 14