我试图从与子文件夹的源目录到目标目录弄清楚如何复制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'))
更新时间:18:21。下面的代码按预期工作,但我想忽略不包含任何include_patterns文件夹(“DWG”,“.DXF”)
shutil
已经包含一个函数ignore_pattern
,所以你不必提供你自己的。直接从documentation:
from shutil import copytree, ignore_patterns copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
这将复制一切,除了
.pyc
文件和文件或目录名称以tmp.
开始
这是一个有点棘手的(而不是严格necessairy)来解释这是怎么回事: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'))