Skip to content

Instantly share code, notes, and snippets.

@sourabhv
Last active August 29, 2015 14:06
Show Gist options
  • Save sourabhv/a492111349c6271a00fd to your computer and use it in GitHub Desktop.
Save sourabhv/a492111349c6271a00fd to your computer and use it in GitHub Desktop.
Print contents of directories in a tree-like format
def tree(path, depth=1, max_depth=100, print_hidden=False, pad_info=[]):
'''Print contents of directories in a tree-like format
By default, it prints upto a depth of 100 and doesn't print hidden files,
ie, files whose name begin with a '.'
returns number of files, number of directories it encountered
'''
fileCount, dirCount = 0, 0
files = sorted(os.listdir(path), key=lambda s: s.lower())
if not print_hidden:
files = [os.path.join(path, x) for x in files if not x.startswith('.')]
for i, file in enumerate(files):
padding = ['| ' if x == 'nl' else ' ' for x in pad_info]
padding = ''.join(padding)
filename = os.path.basename(file)
is_last = i == len(files) - 1
prefix = '`-- ' if is_last else '|-- '
print '%s%s%s' % (padding, prefix, filename)
if os.path.isdir(file):
dirCount += 1
new_pad_info = pad_info + (['l'] if is_last else ['nl'])
fc, dc = tree(os.path.join(path, file), depth=depth+1,
max_depth=max_depth, print_hidden=print_hidden,
pad_info=new_pad_info)
fileCount += fc
dirCount += dc
else:
fileCount += 1
return fileCount, dirCount
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment