gpt4 book ai didi

Python shutil copytree : use ignore function to keep specific files types

转载 作者:太空狗 更新时间:2023-10-29 21:20:39 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何将 CAD 图纸(“.dwg”、“.dxf”)从带有子文件夹的源目录复制到目标目录并保持原始目录和子文件夹结构。

  • 原始目录:H:\Tanzania...\Bagamoyo_Single_line.dw​​g
  • 源目录:H:\CAD\Tanzania...\Bagamoyo_Single_line.dw​​g

我从 @martineau 中找到了以下答案在以下帖子中:Python Factory Function

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

更新时间:18:21。以下代码按预期工作,只是我想忽略不包含任何 include_patterns('.dwg', '.dxf')

的文件夹

最佳答案

shutil 已经包含函数 ignore_patterns,因此您不必提供自己的函数。直接来自 documentation :

from shutil import copytree, ignore_patterns

copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

This will copy everything except .pyc files and files ordirectories whose name starts with tmp.

解释发生了什么有点棘手(而且并非绝对必要):ignore_patterns 返回一个函数 _ignore_patterns 作为它的返回值,这个函数被填充到 copytree作为参数,copytree根据需要调用这个函数,所以你不必知道或关心如何调用这个函数_ignore_patterns。这只是意味着您可以排除某些不需要的 cruft 文件(如 *.pyc)被复制。函数名称 _ignore_patterns 以下划线开头的事实暗示该函数是您可以忽略的实现细节。

copytree 预计文件夹 destination 尚不存在。一旦 copytree 开始工作,这个文件夹及其子文件夹就不会出现问题,copytree 知道如何处理它。

现在编写 include_patterns 是为了做相反的事情:忽略所有未明确包含的内容。但它的工作方式相同:您只需调用它,它会返回一个底层函数,coptytree 知道如何处理该函数:

copytree(source, destination, ignore=include_patterns('*.dwg', '*.dxf'))

关于Python shutil copytree : use ignore function to keep specific files types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42487578/

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