Created
June 2, 2020 02:04
-
-
Save richardbwest/a2f8e56d2894d1671f73841065648d56 to your computer and use it in GitHub Desktop.
Recursive File System Traversal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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