gpt4 book ai didi

python 使用包含模式复制文件

转载 作者:行者123 更新时间:2023-11-30 22:08:53 24 4
gpt4 key购买 nike

我需要使用 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'))

上面的代码从目录复制了除指定格式之外的文件,但我需要像下面这样的东西

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'))

关于python 使用包含模式复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52071642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com