Aro*_*Raj 6 python design-patterns copy include shutil
我需要使用 python 脚本复制包含模式的文件。由于shutil支持ignore_patterns来忽略文件。有没有任何方法可以包含复制文件的模式。否则我必须明确地编写代码吗?
提前致谢
编辑
from shutil import copytree, ignore_patterns
source=r'SOURCE_PATH'
destination=r'DESTINATION_PATH'
copytree(source, destination, ignore=ignore_patterns('*.txt'))
Run Code Online (Sandbox Code Playgroud)
上面的代码从 dir 复制了除指定格式之外的文件,但我需要如下所示的内容
from shutil import copytree, include_patterns
source=r'SOURCE_PATH'
destination=r'DESTINATION_PATH'
copytree(source, destination, ignore=include_patterns('*.txt'))
Run Code Online (Sandbox Code Playgroud)
下面的解决方案工作正常
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)