Skip to content

Instantly share code, notes, and snippets.

@ivanistheone
Created February 27, 2023 17:05
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 ivanistheone/0b9b3c003766f5bc9323cdcb925afafa to your computer and use it in GitHub Desktop.
Save ivanistheone/0b9b3c003766f5bc9323cdcb925afafa to your computer and use it in GitHub Desktop.
Print filesystem tree, similar to command line tool `tree` in UNIX.
#!/usr/bin/env python
import argparse
import os
def tree(directory=".", indent = " "):
"""
Helper function that prints the filesystem tree.
"""
ignorables = ["__pycache__", ".gitignore", ".DS_Store", ".ipynb_checkpoints", ".git", "venv"]
for root, dirs, files in os.walk(directory):
path = root.split(os.sep)
if any(ign in path for ign in ignorables):
continue
print((len(path) - 1) * indent, os.path.basename(root) + "/")
for file in files:
if file in ignorables:
continue
print(len(path) * indent, file)
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog = 'tree', description = 'list contents of directories in a tree-like format.')
parser.add_argument('directory', nargs='?', default=".")
args = parser.parse_args()
tree(args.directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment