我需要使用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'))
上面的代码从dir中复制了文件,除了指定的格式,但是我需要以下内容
from shutil import copytree, include_patterns
source=r'SOURCE_PATH'
destination=r'DESTINATION_PATH'
copytree(source, destination, ignore=include_patterns('*.txt'))
下面的解决方案工作正常
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'))
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句