Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I wrote this piece of code to mimic the *nix tree utility, however, I am not happy with the pad_info=[] part. It's used to make padding according to whether the parents were last child of their parents or not. Is there any alternate (and a more elegant) way to do this?

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
share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.