Skip to content

Instantly share code, notes, and snippets.

@alphazwest
Created May 9, 2022 22:19
Embed
What would you like to do?
import sys
import os
def print_dir_tree(dirname: str, indent: int=0):
# Prints the indendations
for i in range(indent):
print(" ", end="")
# Prints the file names
print(os.path.basename(dirname))
# Recurses on directories and their files
if os.path.isdir(dirname):
# Recurse for each file in a directory
for files in os.listdir(dirname):
print_dir_tree(os.path.join(dirname, files), indent+1)
if __name__ == "__main__":
# Check argument supplied
if len(sys.argv) - 1 != 1:
raise SystemExit("Usage: <python print_dir_tree.py directory>")
# Parse CMD Args
the_dir = sys.argv[1]
# Check directory exists
if not os.path.exists(the_dir):
raise SystemExit(f"The directory: {the_dir} does not exist.")
# runs the program, passing in the name of the directory.
print_dir_tree(the_dir)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment