Skip to content

Commit

Permalink
quick implementation of max_depth for boltons.fileutils.iter_find_files
Browse files Browse the repository at this point in the history
  • Loading branch information
mahmoud committed Dec 3, 2023
1 parent 6cac49c commit 0e4dd35
Showing 1 changed file with 7 additions and 1 deletion.
8 changes: 7 additions & 1 deletion boltons/fileutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -493,7 +493,7 @@ def __exit__(self, exc_type, exc_val, exc_tb):
return


def iter_find_files(directory, patterns, ignored=None, include_dirs=False):
def iter_find_files(directory, patterns, ignored=None, include_dirs=False, max_depth=None):
"""Returns a generator that yields file paths under a *directory*,
matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also
supports *ignored* patterns.
Expand All @@ -507,6 +507,9 @@ def iter_find_files(directory, patterns, ignored=None, include_dirs=False):
glob-formatted patterns to ignore.
include_dirs (bool): Whether to include directories that match
patterns, as well. Defaults to ``False``.
max_depth (int): traverse up to this level of subdirectory.
I.e., 0 for the specified *directory* only, 1 for *directory*
and one level of subdirectory.
For example, finding Python files in the current directory:
Expand All @@ -531,7 +534,10 @@ def iter_find_files(directory, patterns, ignored=None, include_dirs=False):
elif isinstance(ignored, basestring):
ignored = [ignored]
ign_re = re.compile('|'.join([fnmatch.translate(p) for p in ignored]))
start_depth = len(directory.split(os.path.sep))
for root, dirs, files in os.walk(directory):
if max_depth is not None and (len(root.split(os.path.sep)) - start_depth) > max_depth:
continue
if include_dirs:
for basename in dirs:
if pats_re.match(basename):
Expand Down

0 comments on commit 0e4dd35

Please sign in to comment.