您可以使用(ususing?)对内置的^{}函数执行您想要的操作其可选的ignore关键字参数。棘手的部分是,如果给定,它必须是一个可调用的函数,它返回每个目录中应该而不是应该复制的内容,而不是应该复制的内容。在
但是,可以编写一个类似于^{}的工厂函数来创建一个完成所需操作的函数,并将其用作ignore关键字参数的值。在
返回的函数首先通过^{}函数确定要保存的文件,然后将它们从给定目录中的所有文件的列表中删除,除非它们是子目录名,在这种情况下,它们会留在后面的[递归]处理中。(这就是它复制整个树的原因,以及您试图编写自己的copytree()函数时可能出现的错误)。在#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Works in Python 2.7 & 3.x
import fnmatch
from os.path import isdir, join
def include_patterns(*patterns):
""" Function that can be used as shutil.copytree() ignore parameter that
determines which files *not* to ignore, the inverse of "normal" usage.
This is a factory function that creates a function which can be used as a
callable for copytree()'s ignore argument, *not* ignoring files that match
any of the glob-style patterns provided.
‛patterns’ are a sequence of pattern strings used to identify the files to
include when copying the directory tree.
Example usage:
copytree(src_directory, dst_directory,
ignore=include_patterns('*.sldasm', '*.sldprt'))
"""
def _ignore_patterns(path, all_names):
# Determine names which match one or more patterns (that shouldn't be
# ignored).
keep = (name for pattern in patterns
for name in fnmatch.filter(all_names, pattern))
# Ignore file names which *didn't* match any of the patterns given that
# aren't directory names.
dir_names = (name for name in all_names if isdir(join(path, name)))
return set(all_names) - set(keep) - set(dir_names)
return _ignore_patterns
if __name__ == '__main__':
from shutil import copytree, rmtree
import os
src = r'C:\vols\Files\PythonLib\Stack Overflow'
dst = r'C:\vols\Temp\temp\test'
# Make sure the destination folder does not exist.
if os.path.exists(dst) and os.path.isdir(dst):
print('removing existing directory "{}"'.format(dst))
rmtree(dst, ignore_errors=False)
copytree(src, dst, ignore=include_patterns('*.png', '*.gif'))
print('done')