我需要从带有模式的目录中复制文件。由于我的操作如下,
from fnmatch import fnmatch, filter
from os.path import isdir, join
from shutil import copytree, ignore_patterns
def include_patterns(*patterns):
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
src_directory = r'SOURCH_PATH'
dst_directory = r'DST_PATH'
ignored_directory = r'DST_PATH2'
copytree(src_directory, ignored_directory,ignore=ignore_patterns('*.bat'))
copytree(src_directory, dst_directory,ignore=include_patterns('*.xls'))
如果目标目录已存在,Copytree将引发错误。所以我需要执行类似这样的复制
copytree(src_directory, ignored_directory,ignore=ignore_patterns('*.bat'), ignore=include_patterns('*.xls'))
或者是否有任何参数可以同时执行包含模式和排除模式的复制操作?
如何实现?
答案 0 :(得分:0)
假设您想覆盖目标文件夹(如果已经存在),则可以使用以下类似方法轻松解决问题:
if os.path.exists(destination_path):
shutil.rmtree(destination_path)
shutil.copytree(<your_params>)