Skip to content

Instantly share code, notes, and snippets.

@richardbwest
Created June 2, 2020 02:04
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 richardbwest/a2f8e56d2894d1671f73841065648d56 to your computer and use it in GitHub Desktop.
Save richardbwest/a2f8e56d2894d1671f73841065648d56 to your computer and use it in GitHub Desktop.
Recursive File System Traversal
# Adapted from - http://openbookproject.net/thinkcs/python/english3e/recursion.html
def get_dirlist(path):
"""
Return a sorted list of all entries in path.
This returns just the names, not the full path to the names.
"""
try:
dirlist = os.listdir(path)
dirlist.sort()
return dirlist
except:
return []
def print_files(path, prefix = ""):
""" Print recursive listing of contents of path """
if prefix == "": # Detect outermost call, print a heading
print("Folder listing for", path)
prefix = "| "
dirlist = get_dirlist(path)
for f in dirlist:
print(prefix+f) # Print the line
fullname = os.path.join(path, f) # Turn name into full pathname
if os.path.isdir(fullname): # If a directory, recurse.
print_files(fullname, prefix + "| ")
print_files("c:\\") # Replace with the folder / drive path you want to traverse
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment