python使用include模式复制文件

时间:2018-08-29 07:18:03

标签: python design-patterns copy include shutil

我需要使用python脚本复制包含模式的文件。由于shutil支持ignore_patterns来忽略文件。是否有任何方法包括复制文件的模式。 否则,我必须显式地编写代码吗?

预先感谢

编辑

from shutil import copytree, ignore_patterns

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

上面的代码从dir中复制了文件,除了指定的格式,但是我在下面需要这样的东西

from shutil import copytree, include_patterns

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

3 个答案:

答案 0 :(得分:1)

我想这里已经回答了这个问题。请检查 。

Python shutil copytree: use ignore function to keep specific files types

答案 1 :(得分:1)

shutil中没有这样的支持,除非您用自己的方法使ignore重载。但是,例如,使用glob可能要简单得多。

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

答案 2 :(得分:0)

以下解决方案效果很好

 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'))