Hack with os.walk()

Michael Spencer mahs at telcopartners.com
Sat Feb 12 19:54:03 EST 2005


Tim Peters wrote:
> [Frans Englich]
> ...
> 
[snip]
> 
> class HasPath:
>     def __init__(self, path):
>         self.path = path
> 
>     def __lt__(self, other):
>         return self.path < other.path
> 
> class Directory(HasPath):
>     def __init__(self, path):
>         HasPath.__init__(self, path)
>         self.files = [] # list of File objects
>         self.subdirs =  [] # list of sub-Directory objects
> 
> class File(HasPath):
>     pass
> 
[snip]
> 
> def build_tree(path, Directory=Directory, File=File):
>     top = Directory(path)
>     path2dir = {path: top}
>     for root, dirs, files in os.walk(path):
>         dirobj = path2dir[root]
>         for name in dirs:
>             subdirobj = Directory(os.path.join(root, name))
>             path2dir[subdirobj.path] = subdirobj
>             dirobj.subdirs.append(subdirobj)
>         for name in files:
>             dirobj.files.append(File(os.path.join(root, name)))
>     return top
> 
> That looks short and sweet to me.  It could be made shorter, but not
> without losing clarity to my eyes.

The aforementioned path class makes this even easier.  No need to build the tree 
- that is done automatically by the path constuctor:

ListingDirectory can then inherit from path.path with few changes:

from path import path

libpath = r"C:\Python24\Lib"

class ListingDirectory(path):
     # Display directory tree as a tree, with 4-space indents.
     # Files listed before subdirectories, both in alphabetical order.
     # Full path displayed for topmost directory, base names for all
     # other entries.  Directories listed with trailing os.sep.
     def display(self, level=0):

         name = self.abspath()   # path method
         if level:
             name = self.basename() # path method
         print "%s%s%s" % (' ' * level, name, os.sep)
         for f in self.files():
             print "%s%s" % (' ' * (level + 4), f.basename())  path method
         for d in self.dirs():  # path.dirs returns an iterator over path objects
             ListingDirectory(d).display(level + 4)

mytree = ListingDirectory(libpath)
mytree.display()

[snip about 15000 lines...]

Michael




More information about the Python-list mailing list