Skip to content

Instantly share code, notes, and snippets.

@nishidy
Last active February 10, 2016 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishidy/391c2eff1ae9ad45b4dc to your computer and use it in GitHub Desktop.
Save nishidy/391c2eff1ae9ad45b4dc to your computer and use it in GitHub Desktop.
Nicer os.walk
import os,re
from functools import reduce
def stroll(topdir,no_root=[],yes_root=[],no_path=[],yes_path=[],no_file=[],yes_file=[],sortby=os.path.basename,reverse=False,ignorecase=True):
T=True
F=False
I=ignorecase
no_root.append("\..")
def se(e,s,i):
if i:
return re.search(e,s,re.IGNORECASE)
else:
return re.search(e,s)
for root, dirs, files in os.walk(topdir,topdown=True):
if no_path:
if reduce(lambda b,p: T if se(p,root,I) else b, no_path, F):
continue
if yes_path:
if reduce(lambda b,p: F if se(p,root,I) else b, yes_path, T):
continue
if no_root:
s=os.path.basename(root)
if reduce(lambda b,r: T if se(r,s,I) else b, no_root, F):
continue
if yes_root:
s=os.path.basename(root)
if reduce(lambda b,r: F if se(r,s,I) else b, yes_root, T):
continue
if no_file:
for fname in files[:]:
if reduce(lambda b,f: T if se(f,fname,I) else b, no_file, F):
files.remove(fname)
if yes_file:
for fname in files[:]:
if reduce(lambda b,f: F if se(f,fname,I) else b, yes_file, T):
files.remove(fname)
dirs.sort(key=lambda x: sortby(os.path.join(root,x)),reverse=reverse)
files.sort(key=lambda x: sortby(os.path.join(root,x)),reverse=reverse)
print(root)
for filename in files:
yield root, filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment