Ascii Representation Of A
Directory Tree... ( Python ) |
||
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 Posted by: Jaroslaw
Frycz |
||
Ascii Representation Of A
Directory Tree... ( Python ) | ||