Skip to content

Instantly share code, notes, and snippets.

@bpeterso2000
Last active December 5, 2022 02:24
Show Gist options
  • Save bpeterso2000/8033539 to your computer and use it in GitHub Desktop.
Save bpeterso2000/8033539 to your computer and use it in GitHub Desktop.
Recursively walk a directory to a specified depth
" Reference: http://stackoverflow.com/questions/7159607 "
import os
import sys
def listdir(path):
"""
recursively walk directory to specified depth
:param path: (str) path to list files from
:yields: (str) filename, including path
"""
for filename in os.listdir(path):
yield os.path.join(path, filename)
def walk(path='.', depth=None):
"""
recursively walk directory to specified depth
:param path: (str) the base path to start walking from
:param depth: (None or int) max. recursive depth, None = no limit
:yields: (str) filename, including path
"""
if depth and depth == 1:
for filename in listdir(path):
yield filename
else:
top_pathlen = len(path) + len(os.path.sep)
for dirpath, dirnames, filenames in os.walk(path):
dirlevel = dirpath[top_pathlen:].count(os.path.sep)
if depth and dirlevel >= depth:
dirnames[:] = []
else:
for filename in filenames:
yield os.path.join(dirpath, filename)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('path', nargs='?', default='.', help=(
"path to list files from (defaults to current directory)"))
parser.add_argument('-d', '--depth', type=int, default=0, help=(
"maximum level of sub-directories to decend"
"(defaults to unlimited)."))
parser.add_argument('-v', '--version', action='version',
version='%(prog)s ' + __version__)
args = parser.parse_args()
for filename in walk(args.path, args.depth):
print(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment