[英]Get also elements that don't match 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
工作正常。 但我也想访问与过滤器不匹配的元素。
有人可以提供一些帮助吗? 我可以在循环中构建一个正则表达式,但必须有一个更简单的解决方案,对吗?
如果顺序无关紧要,请使用一组:
goodfiles = fnmatch.filter(files, pattern)
badfiles = set(files).difference(goodfiles)
也可以使用os.walk
循环中的另一个循环:
goodfiles = []
badfiles = []
for f in files:
if fnmatch.fnmatch(f, pattern):
goodfiles.append(f)
else:
badfiles.append(f)
注意:使用此解决方案,您只需遍历文件列表一次。 其实os.path.join
部分可以移到上面的循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.