Travel directory tree with limited recursion depth

I think the easiest and most stable approach would be to copy the functionality of os.walk straight out of the source and insert your own depth-controlling parameter. import os import os.path as path def walk(top, topdown=True, onerror=None, followlinks=False, maxdepth=None): islink, join, isdir = path.islink, path.join, path.isdir try: names = os.listdir(top) except OSError, err: if onerror … Read more

Filtering os.walk() dirs and files

This solution uses fnmatch.translate to convert glob patterns to regular expressions (it assumes the includes only is used for files): import fnmatch import os import os.path import re includes = [‘*.doc’, ‘*.odt’] # for files only excludes = [‘/home/paulo-freitas/Documents’] # for dirs and files # transform glob patterns to regular expressions includes = r’|’.join([fnmatch.translate(x) for … Read more