我试图编写一个简单的脚本,将文件从一个文件夹移到另一个文件夹,并过滤掉不必要的内容。我正在使用下面的代码,但是收到了一个错误
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'发布于 2014-10-03 15:25:19
您的Python版本太老了。来自 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这将适用于Python2.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了(因为您只是在测试特定的扩展),并且使用了与较早版本兼容的语法。
https://stackoverflow.com/questions/26181828
复制相似问题