Content of file to tree format using python
Question: I have a file containing a file "dir.txt" with the below data:

    
    
    /home/abc/a.txt
    /home/abc/b.txt
    /home/xyz/test
    /home/xyz/test/d.txt
    /home/xyz/test/e.txt
    /home/xyz/test/f.txt
    /home/xyz
    /home/xyz/g.txt
    

I want to parse the file and get the output like

    
    
    /home/abc/a.txt
              b.txt
    /home/xyz/test/d.txt
                   e.txt
                   f.txt
    /home/xyz/g.txt
    

Using python, basically need to print the content in a tree format. How would
I process it?


Answer: you need to use `os.path.split` on every path, find the first dirname and
print path as it is. find it length and print so many spaces before next
basename, on change of the dirname repeat as before.

    
    
    >>> import os.path    
    >>> olddir = None
    >>> for name in open('input.txt'):
        dirname, fname = os.path.split(name)
        if olddir != dirname:
            prefix = ' ' * (len(dirname) +1)
            olddir = dirname
            print(name)
        else:
            print(prefix + fname)
    
    
    /home/abc/a.txt
              b.txt
    /home/xyz/test/d.txt
                   e.txt
                   f.txt
    /home/xyz/g.txt
    

