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
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With