5

I need to copy the files with include pattern using python script. Since shutil supports ignore_patterns to ignore the file. Is there any method to include the pattern to copy the files. Otherwise do I have to write the code explicitly?.

Thanks in advance

EDIT

from shutil import copytree, ignore_patterns

source=r'SOURCE_PATH'
destination=r'DESTINATION_PATH'
copytree(source, destination, ignore=ignore_patterns('*.txt'))

The above code copied the files from dir except specified format, But I need something like this below

from shutil import copytree, include_patterns

source=r'SOURCE_PATH'
destination=r'DESTINATION_PATH'
copytree(source, destination, ignore=include_patterns('*.txt'))
ArockiaRaj
  • 588
  • 4
  • 17

2 Answers2

5

The below solution works fine

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

    def include_patterns(*patterns):
        """Factory function that can be used with copytree() ignore parameter.

        Arguments define a sequence of glob-style patterns
        that are used to specify what files to NOT ignore.
        Creates and returns a function that determines this for each directory
        in the file hierarchy rooted at the source directory when used with
        shutil.copytree().
        """
        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

    # sample usage

    copytree(src_directory, dst_directory,
         ignore=include_patterns('*.dwg', '*.dxf'))
ArockiaRaj
  • 588
  • 4
  • 17
1

There is no such support in shutil, unless you overload the ignore with your own method. But using glob probably is much simpler, for example.

import glob
import shutil
dest_dir = "C:/test"
for file in glob.glob(r'C:/*.txt'):
    print(file)
    shutil.copy(file, dest_dir)

python copy files by wildcards

Radan
  • 1,630
  • 5
  • 25
  • 38