get also element that don't match fnmatch

寵の児 提交于 2019-12-07 13:51:27

问题


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?

Thanks in advance! Lars


回答1:


If order doesn't matter, use a set:

goodfiles = fnmatch.filter(files, pattern)
badfiles = set(files).difference(goodfiles)



回答2:


Another loop inside the os.walk loop can also be used:

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.



来源:https://stackoverflow.com/questions/8645303/get-also-element-that-dont-match-fnmatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!