Skip to content

Instantly share code, notes, and snippets.

@chergert
Created September 21, 2008 08:05
Show Gist options
  • Save chergert/11851 to your computer and use it in GitHub Desktop.
Save chergert/11851 to your computer and use it in GitHub Desktop.
import os
def moonWalk(path, **kwargs):
"""
Generator for recursively walking a directory tree with additional
options compared to os.walk.
@path: a str containing the root directoyr or file
@kwargs: The following args are supported:
ignoredot=False -- ignores dot folders during recursion
maxdepth=-1 -- sets the maximum recursions to be performed
Returns: yields tuple of (str,[str],[str]) containing the root dir
as the first item, list of files as the second, and list of
dirs as the third.
"""
if not os.path.isdir(path):
raise StopIteration
ignoredot = kwargs.get('ignoredot', False)
maxdepth = kwargs.get('maxdepth', -1)
curdepth = kwargs.get('curdepth', -1)
kwargs['curdepth'] = curdepth + 1
if maxdepth > -1 and curdepth > maxdepth:
raise StopIteration
matches = lambda p: not ignoredot or not p.startswith('.')
dirs = []
files = []
for child in os.listdir(path):
if matches(child):
fullpath = os.path.join(path, child)
if os.path.isdir(fullpath):
dirs.append(child)
else:
files.append(child)
yield (path, dirs, files)
for child in dirs:
fullpath = os.path.join(path, child)
for item in moonWalk(fullpath, **kwargs):
yield item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment