Pet*_*son 10 python ignore copytree
我试图弄清楚如何将CAD图纸(".dwg",".dxf")从包含子文件夹的源目录复制到目标目录,并维护原始目录和子文件夹结构.
我在以下帖子中找到了@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
,所以你不必提供自己的功能.直接来自文档:
Run Code Online (Sandbox Code Playgroud)from shutil import copytree, ignore_patterns copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
这将复制除
.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)