1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
   | 
 
  """ list a directory in tree way.
  children(path):     map(lambda name: tree(path, name), listdir(path))
  tree(parent, dir_name):     if is_file(parent, dir_name):         return {'name': dir_name, 'children': []}     else:         children = children(join(parent, dir_name))         return {'name': dir_name, 'children': children} """ import os import functools as fp
  I_branch = "│   " T_branch = "├── " L_branch = "└── " SPACER = "    "
  def _children(path):     return map(lambda filename: tree_format(path, filename), os.listdir(path))
  def tree_format(parent, dir_name):     path = os.path.join(parent, dir_name)     is_file = os.path.isfile(path)     children = [] if is_file else _children(path)     return {'name': dir_name, 'children': list(children)}
  def render_tree(tr):     name = tr['name']     children = tr['children']     return [name] + fp.reduce(lambda l, r: l + r,                               map(lambda arg: render(len(children))(*arg),                                   enumerate(children)),                               [])
  def render(length):     def prefix(index, child):         is_last = (index == length - 1)         prefix_first = L_branch if is_last else T_branch         prefix_rest = SPACER if is_last else I_branch         tr = render_tree(child)         head = prefix_first + tr[0]         tail = [prefix_rest + t for t in tr[1:]]         return [head] + tail     return prefix
  if __name__ == "__main__":     print '\n'.join(render_tree(tree('', sys.argv[1])))
  $ python3 tree.py .  . ├── tree.py ├── files.py ├── lists.py ├── tuples.py ├── resources │   └── README.md ├── recursion.py └── data     ├── output.txt     └── data.txt
 
  |