Ascii Representation Of A Directory Tree... ( Python )

Download this scriptClick here to print the script.


Author: Don Perterson

Description:

This file defines the class Tree, which will return an ASCII representation of a directory tree (each line represents one directory).

Script:


import os

class Tree:
    def __init__(self, dir):
        self.dir = dir
        if not os.path.isdir(dir):
            raise "Bad data", "parameter is not a directory"
        self.indent_level     = 0
        self.indent_increment = 4
        self.list             = []
        self.root             = dir

    def SetIndentIncrement(self, indent_increment = 2):
        if indent_increment < 1:
            raise "Bad data", "indent increment must be > 0"
        self.indent_increment = indent_increment

    def Get(self):
        '''Returns the directory tree as a list of lines.
        '''
        self.list.append(self.dir)
        self.__get_dir(dir)
        return self.list

    def __get_dir(self, dir):
        '''Return the indicated directory and all subdirectories.
        '''
        currdir = os.getcwd()
        print "xx currdir =", currdir
        newdir = os.path.join(self.root, dir)
        print "xx", newdir
        os.chdir(newdir)
        dirlist = os.listdir(".")
        dirlist.sort()
        self.indent_level = self.indent_level + self.indent_increment
        for ix in xrange(len(dirlist)):
            if not os.path.isdir(dirlist[ix]):
                continue
            num_indents = self.indent_level / self.indent_increment
            str = " " * self.indent_increment
            str = str * num_indents + dirlist[ix]
            self.list.append(str)
            self.__get_dir(dirlist[ix])
        self.indent_level = self.indent_level - self.indent_increment
        os.chdir("..")

if __name__ == "__main__":
    import sys
    dir = sys.argv[1]
    print dir
    t = Tree(dir)
    lines = t.Get()
    for line in lines:
        print line
        

Keywords: No Keywords





Posted by: Bobby Martin     
Date: 11/16/2004 11:14:49 AM
Comment: In this code:
def Get(self):
'''Returns the directory tree as a list of lines.
'''
self.list.append(self.dir)
self.__get_dir(dir)
return self.list

the call to self.__get_dir(dir) should be self.__get_dir(self.dir). The code as written causes an error when you try to call startswith on a directory object, at least when running on cygwin under WinXP

Posted by: Jaroslaw Frycz     
Date: 5/2/2005 5:02:09 AM
Comment: Another error - in function __get__dir should be
>>>newdir = os.path.join(currdir, dir)
instead of
>>>newdir = os.path.join(self.root, dir)

and
all code from line
>>>os.chdir(newdir)
should be in 'try ... exception' due to 'Permission denied' for example to "System Volume Information" directory





Full Name:

Email Address:

Message:

Ascii Representation Of A Directory Tree... ( Python )



Go back to the top of the script.