Python shutil.ignore_patterns错误

时间:2014-10-03 15:18:34

标签: python ignore shutil copytree

我试图编写一个简单的脚本来将文件从一个文件夹移动到另一个文件夹并过滤掉不必要的东西。我使用下面的代码,但收到错误

import shutil
import errno

def copy(src, dest):
    try:
        shutil.copytree(src, dest, ignore=shutil.ignore_patterns('*.mp4', '*.bak'))
    except OSError:
        if OSError.errno == errno.ENOTDIR:
            shutil.copy(src, dest)
        else:
             print("Directory not copied. Error: %s" % OSError)

src = raw_input("Please enter a source: ")
dest = raw_input("Please enter a destination: ")

copy(src, dest)

我得到的错误是:

Traceback (most recent call last):   
File "/Users/XXX/PycharmProjects/Folders/Fold.py", line 29,
  in <module>
  copy(src, dest)   
File "/Users/XXX/PycharmProjects/Folders/Fold.py", line 17,
  in copy
  ignore_pat = shutil.ignore_patterns('*.mp4', '*.bak') 
AttributeError: 'module' object has no attribute 'ignore_patterns'

1 个答案:

答案 0 :(得分:1)

你的Python版本太旧了。来自shutil.ignore_patterns() documentation

  

2.6版中的新功能。

在较旧的Python版本上复制该方法很容易:

import fnmatch 

def ignore_patterns(*patterns):
    """Function that can be used as copytree() ignore parameter.

    Patterns is a sequence of glob-style patterns
    that are used to exclude files"""
    def _ignore_patterns(path, names):
        ignored_names = []
        for pattern in patterns:
            ignored_names.extend(fnmatch.filter(names, pattern))
        return set(ignored_names)
    return _ignore_patterns

这将在Python 2.4和更新版本上运行。

要将其简化为您的特定代码:

def copy(src, dest):
    def ignore(path, names):
        ignored = set()
        for name in names:
            if name.endswith('.mp4') or name.endswith('.bak'):
                ignored.add(name)
        return ignored

    try:
        shutil.copytree(src, dest, ignore=ignore)
    except OSError:
        if OSError.errno == errno.ENOTDIR:
            shutil.copy(src, dest)
        else:
             print("Directory not copied. Error: %s" % OSError)

这根本不再使用fnmatch(因为您只测试特定扩展名)并使用与旧版Python兼容的语法。