using os.walk to generate objects

Joe Hrbek joe.hrbek at gmail.com
Wed Dec 3 13:40:14 EST 2008


The code below works (in linux), but I'm wondering if there is a
better/easier/cleaner way?  It works on directory trees that don't
have a lot of "."s in them or other special characters. I haven't
implemented a good handler for that yet, so if you run this in your
system, choose/make a simple directory structure to use as your root
for os.walk().  Also, you must start from the top most directory
level, like /test.  /tmp/test as a root will not work (yet). :)

I wanted to know if I could use os.walk() to construct an object based
off of a directory tree. So, the following path: "/test/home/user"
would get converted into "test.home.user" and I could then work with
it that way in my python program, attaching attributes to those
"directories" that I could use to keep track of things.  This was more
of an exercise in learning than anything, I wanted to see if I could
do it.  I've never used "type()" before to create new objects, so
really that was the point.  Can I do this an easier way though?

----
import os
from os.path import join, getsize

def remove_hidden(dirlist):
    """For a list containing directory names, remove
       any that start with a dot"""
    dirlist[:] = [d for d in dirlist if not d.startswith('.')]

def recurse_dir_tree(context,dirs):
    """recurse through tree structure and add attributes
        as necessary"""
    for directory in dirs:
        fixedDir = directory.replace('.','_').lower()
        #print ("directory is:%s" % fixedDir)
        newAttrObj = type(("%s" % fixedDir),(),{})
        if newAttrObj.__name__:
            #print newAttrObj.__name__
            #print "context is "+context
            print "tree."+context
            setattr(eval
("tree."+context),newAttrObj.__name__,newAttrObj)

class Tree(object):
    def __init__(self,wd):
        self.__name__ = wd


pathroot = '/test'
tree = Tree(pathroot)


for root, dirs, files in os.walk(pathroot):
    tree.currentRoot = ".".join(map(str,root.split('/')[1:]))
    tree.currentRoot = tree.currentRoot.lower()
    print "currentRoot:" + tree.currentRoot
    if pathroot == root:
        #this is the start of the object tree
        tree.baseRoot = pathroot.split('/')[1]
        newAttrObj = type(("%s" % tree.currentRoot),(),{})
        setattr(tree,newAttrObj.__name__,newAttrObj)
    #print dirs
    remove_hidden(dirs)
    #print dirs
    if dirs:
        recurse_dir_tree(tree.currentRoot,dirs)



More information about the Python-list mailing list