1

I need to copy the files from a directory with patterns. Since I did as below,

from fnmatch import fnmatch, filter
from os.path import isdir, join
from shutil import copytree, ignore_patterns

def include_patterns(*patterns):

    def _ignore_patterns(path, names):
        keep = set(name for pattern in patterns
                            for name in filter(names, pattern))
        ignore = set(name for name in names
                        if name not in keep and not isdir(join(path, name)))
        return ignore
    return _ignore_patterns


src_directory = r'SOURCH_PATH'
dst_directory = r'DST_PATH'
ignored_directory = r'DST_PATH2'
copytree(src_directory, ignored_directory,ignore=ignore_patterns('*.bat'))
copytree(src_directory, dst_directory,ignore=include_patterns('*.xls'))

Copytree will raise error if the destination directory already exist. So I need to perform copy something like this

copytree(src_directory, ignored_directory,ignore=ignore_patterns('*.bat'), ignore=include_patterns('*.xls'))

or is there any params to perform the copy operation with both include pattern & exclude pattern?

How to achieve this?

ArockiaRaj
  • 588
  • 4
  • 17

1 Answers1

-1

Assuming you want to overwrite the destination folder if already exists you could easily solve your problem with something like this:

if os.path.exists(destination_path):
    shutil.rmtree(destination_path)
shutil.copytree(<your_params>)
rakwaht
  • 3,666
  • 3
  • 28
  • 45
  • I should not remove the folder, Is there any possibility to ignore them? @rakwaht – ArockiaRaj Aug 30 '18 at 13:30
  • @Jarvis I don't get what you want to do. When you are copying dirA to dirB but dirB already exists and contains stuff what do you think should happen? – rakwaht Aug 30 '18 at 13:32
  • Yaa it shouldn't happen, But I want to perform the copy operation with both include and exclude pattern at the same time . Is it possible? – ArockiaRaj Aug 30 '18 at 13:36
  • I don't understand really. Please edit your question and explain (maybe with an example) what's your problem – rakwaht Aug 30 '18 at 14:12
  • They're asking for something similar to what's possible in rsync where you can chain excludes and includes. This is useful for scenarios like needing all the files of specific subdirectories while omitting extensions like '*.bak'. It's still possible to copy the same files with only ignore or include, but it'll take several more "flat" calls rather than using fewer calls with more complex recursion. – David Rachwalik Dec 28 '22 at 05:19