Skip to content

Instantly share code, notes, and snippets.

@alphazwest
Created May 9, 2022 22:19
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 alphazwest/d46922d0a68f58e9a31bc169427fdb92 to your computer and use it in GitHub Desktop.
Save alphazwest/d46922d0a68f58e9a31bc169427fdb92 to your computer and use it in GitHub Desktop.
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