Python shutil copytree:使用ignore函数保留特定的文件类型

Pet*_*son 10 python ignore copytree

我试图弄清楚如何将CAD图纸(".dwg",".dxf")从包含子文件夹的源目录复制到目标目录,并维护原始目录和子文件夹结构.

  • 原始目录:H:\ Tanzania ...\Bagamoyo_Single_line.dw​​g
  • 源目录:H:\ CAD\Tanzania ...\Bagamoyo_Single_line.dw​​g

我在以下帖子中找到了@martineau的以下答案:Python Factory Function

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'))
Run Code Online (Sandbox Code Playgroud)

更新:18:21.下面的代码按预期工作,除了我想忽略不包含任何include_patterns('. dwg','..dxf')的文件夹

Jan*_*Jan 19

shutil已经包含一个功能ignore_pattern,所以你不必提供自己的功能.直接来自文档:

from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
Run Code Online (Sandbox Code Playgroud)

这将复制除.pyc名称以文件开头的文件和文件或目录之外的所有内容tmp.

解释发生了什么有点棘手(并不是非常必要):ignore_patterns返回一个函数_ignore_patterns作为其返回值,此函数copytree作为参数填入,并copytree根据需要调用此函数,因此您不必知道或关心如何调用此功能_ignore_patterns.它只是意味着您可以排除某些不需要的*.pyc副本文件(如)被复制.函数名称_ignore_patterns以下划线开头的事实暗示该函数是您可能忽略的实现细节.

copytree期望该文件夹destination尚不存在.这个文件夹及其子文件夹一旦copytree开始工作就会存在,并且copytree知道如何处理它并不是问题.

现在include_patterns写的是相反的做法:忽略未明确包含的所有内容.但它的工作原理相同:你只需要调用它,它会在引擎盖下返回一个函数,并coptytree知道如何处理该函数:

copytree(source, destination, ignore=include_patterns('*.dwg', '*.dxf'))
Run Code Online (Sandbox Code Playgroud)

  • @KcFnMi,您需要从列表中解压值。使用:`ignore_patterns(*mylist)`。我测试了它并且它有效。 (2认同)