【问题标题】:python copying the files with include patternpython使用包含模式复制文件
【发布时间】:2018-08-29 07:18:03
【问题描述】:

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

【问题讨论】:

  • 你有正在处理的代码吗?
  • glob 怎么样?
  • 查看我的编辑@Radan
  • shutil 中没有 include_patterns,这是您想要实现的目标吗?
  • 我需要复制带有 cetain 模式的文件,这些文件需要单独复制 @Radan

标签: python design-patterns copy include shutil


【解决方案1】:

以下解决方案效果很好

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

【讨论】:

    【解决方案2】:

    我猜这个问题已经在这里得到了回答。请检查 。

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

    【讨论】:

    • 如果我尝试上面的代码,我会遇到 NameError: name 'include_patterns' is not defined
    • 使用上述解决方案@NarayanP 工作正常
    【解决方案3】:

    shutil 中没有这样的支持,除非您使用自己的方法重载忽略。但是,例如,使用 glob 可能要简单得多。

    import glob
    import shutil
    dest_dir = "C:/test"
    for file in glob.glob(r'C:/*.txt'):
        print(file)
        shutil.copy(file, dest_dir)
    

    python copy files by wildcards

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      • 2021-10-13
      • 2021-10-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      相关资源
      最近更新 更多