dir2tree

A simple script to convert a list of paths (like the output of find, say) into a more tree oriented list, so it's a little easier to see the underlying structure.

#!/usr/bin/env python

import sys

The way this works is to keep track of the last full path displayed as a list of components with slashes at the ends of directory components (eg ["usr/", "bin/", "vi"]):

path = []

We then read every path on stdin:

for file in sys.stdin.readlines():
    file = file.rstrip()
    filepaths = file.split("/")
    filepaths = [ f+"/" for f in filepaths[:-1]] + [filepaths[-1]]

...and construct the corresponding list for that path.

We then match the path we just generated with the path so far, and see where they start to differ:

    skip = 0
    for i,p in enumerate(path):
        if p != filepaths[i]:
            skip = i
            break

...cut off the now irrelevant parts:

    path = path[:skip]

...and print out (and append) each of the additional path components, indented appropriately.

    for x in filepaths[skip:]:
        print "\t"*len(path) + x
        path.append(x)
Powered by Sputnik | XHTML 1.1