Python shutil.ignore_模式错误
我正在尝试编写一个简单的脚本,将文件从一个文件夹移动到另一个文件夹,并过滤掉不必要的内容。我正在使用下面的代码,但收到一个错误Python shutil.ignore_模式错误,python,ignore,shutil,copytree,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
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'
回溯(最近一次呼叫最后一次):
文件“/Users/XXX/PycharmProjects/Folders/Fold.py”,第29行,
在里面
副本(src、dest)
文件“/Users/XXX/PycharmProjects/Folders/Fold.py”,第17行,
副本
忽略模式('*.mp4','*.bak'))
AttributeError:“模块”对象没有“忽略模式”属性
您的Python版本太旧。从:
版本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
(因为您只测试特定的扩展),并且使用与旧Python版本兼容的语法。您使用的Python版本是什么ignore_patterns
显然是在2.6中添加的。谢谢,我没有意识到我的PyCharm使用的是2.5.6!