Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 812
LarsVegas Avatar asked Jan 22 '26 23:01

LarsVegas


2 Answers

If order doesn't matter, use a set:

goodfiles = fnmatch.filter(files, pattern)
badfiles = set(files).difference(goodfiles)
like image 117
kojiro Avatar answered Jan 25 '26 13:01

kojiro


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.

like image 38
jcollado Avatar answered Jan 25 '26 14:01

jcollado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!