[英]Get also elements that don't match fnmatch
I'm using a recursive glob to find and copy files from a drive to another我正在使用递归全局查找文件并将文件从驱动器复制到另一个驱动器
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
Works fine.工作正常。 But I also want to have access to the elements that don't match the filter.
但我也想访问与过滤器不匹配的元素。
Can someone offer some help?有人可以提供一些帮助吗? I could build a regex within the loop, but there must be a simpler solution, right?
我可以在循环中构建一个正则表达式,但必须有一个更简单的解决方案,对吗?
If order doesn't matter, use a set:如果顺序无关紧要,请使用一组:
goodfiles = fnmatch.filter(files, pattern)
badfiles = set(files).difference(goodfiles)
Another loop inside the os.walk
loop can also be used:也可以使用
os.walk
循环中的另一个循环:
goodfiles = []
badfiles = []
for f in files:
if fnmatch.fnmatch(f, pattern):
goodfiles.append(f)
else:
badfiles.append(f)
Note: With this solution you have to iterate through the list of files just once.注意:使用此解决方案,您只需遍历文件列表一次。 In fact, the
os.path.join
part can be moved to the loop above.其实
os.path.join
部分可以移到上面的循环中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.