Skip to content

Instantly share code, notes, and snippets.

@macro1
Created November 1, 2015 02:31
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 macro1/17c85e26ecb25b9169f3 to your computer and use it in GitHub Desktop.
Save macro1/17c85e26ecb25b9169f3 to your computer and use it in GitHub Desktop.
Reimplementation of basic Unix-style tree command in Python.
#! /usr/bin/env python
"""Reimplementation of basic Unix-style tree command in Python 3."""
import argparse
from os import listdir, path
def print_tree(top, prefix=''):
print('{prefix}{base_name}'.format(
prefix=prefix, base_name=path.basename(top)))
prefix = prefix.replace('└──', ' ').replace('├──', '| ')
try:
children = listdir(top)
except OSError as e:
return
children = sorted(children)
for name in children[:-1]:
print_tree(path.sep.join([top, name]),
prefix='{prefix}├── '.format(prefix=prefix))
if children:
print_tree(path.sep.join([top, children[-1]]),
prefix='{prefix}└── '.format(prefix=prefix))
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('directory')
args = parser.parse_args()
print_tree(args.directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment