代码之家  ›  专栏  ›  技术社区  ›  e.matt

复制特定子文件夹Python[复制]

  •  0
  • e.matt  · 技术社区  · 7 年前

    我正在尝试找出如何将CAD图形(“.dwg”、“.dxf”)从包含子文件夹的源目录复制到目标目录,并保持原始目录和子文件夹结构。

    • 原始目录:H:\坦桑尼亚…\Bagamoyo_Single_line.dwg
    • 源目录:H:\CAD\Tanzania…\Bagamoyo_Single_line.dwg

    我找到了下面的答案 @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'))
    

    更新时间:18:21。以下代码按预期工作,但我希望忽略不包含任何include_模式的文件夹(' .dwg',' .dxf')

    0 回复  |  直到 8 年前
        1
  •  18
  •   Jan    9 年前

    shutil 已包含函数 ignore_pattern ,所以你不必自己提供。直接从 documentation :

    from shutil import copytree, ignore_patterns
    
    copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
    

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

    要解释发生了什么有点棘手(而且不是绝对必要的): ignore_patterns 返回函数 _ignore_patterns 作为它的返回值,这个函数被填充到 copytree 作为参数,以及 复制树 根据需要调用此函数,因此您不必知道或关心如何调用此函数 _忽略模式 . 它只是意味着您可以排除某些不需要的cruft文件(例如 *.pyc )不会被复制。函数的名称 _忽略模式 以下划线开头表示此函数是一个可以忽略的实现细节。

    复制树 期望文件夹 destination 还不存在。这个文件夹和它的子文件夹已经存在,这不是问题。 复制树 开始工作, 复制树 知道怎么处理。

    现在 include_patterns 是为了做相反的事情:忽略所有未明确包含的内容。但它的工作方式是一样的:你只要调用它,它就会在引擎盖下返回一个函数,然后 coptytree 知道如何处理该函数:

    copytree(source, destination, ignore=include_patterns('*.dwg', '*.dxf'))