2014-10-03 54 views
1

我想写一个简单的脚本来将文件从一个文件夹移动到另一个文件夹并过滤不必要的东西。我使用下面的代码,但接收到错误Python shutil.ignore_patterns错误

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' 
+0

您使用的是什么版本的Python? 2.6中明显增加了“ignore_patterns”。 – 2014-10-03 15:22:22

+0

谢谢,我没有意识到我的PyCharm使用2.5.6! – Nick 2014-10-03 20:47:39

回答

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版本兼容。

+0

谢谢,这有帮助 – Nick 2014-10-03 20:48:14