获取不匹配fnmatch的元素
我正在使用递归的方式来查找并复制文件,从一个驱动器到另一个驱动器。
def recursive_glob(treeroot, pattern):
results = []
for base, dirs, files in os.walk(treeroot):
goodfiles = fnmatch.filter(files, pattern)
results.extend(os.path.join(base, f) for f in goodfiles)
return results
这个方法运行得很好。不过,我还想获取那些不符合过滤条件的文件。
有没有人能帮帮我?我可以在循环中构建一个正则表达式,但应该有更简单的办法,对吧?
2 个回答
1
在os.walk
这个循环里面,还可以再加一个循环来使用:
goodfiles = []
badfiles = []
for f in files:
if fnmatch.fnmatch(f, pattern):
goodfiles.append(f)
else:
badfiles.append(f)
注意:用这个方法你只需要遍历文件列表一次。实际上,os.path.join
的部分可以放到上面的循环里去。
5
如果顺序不重要,可以使用集合(set):
goodfiles = fnmatch.filter(files, pattern)
badfiles = set(files).difference(goodfiles)