A simple generator application

Doug Fort doug.fort at verizon.net
Sat Oct 12 13:22:40 EDT 2002


<can't get PAN to attach, here's the text>

#!/usr/bin/env python
"""
A generator that walks a directory tree while returning pathnames

I release this code to the public. Do what you want with it. No warranty
or support is implied or available.
"""
from __future__ import generators # needed for Python 2.2

__copyright__ = "Copyright (C) Doug Fort -- Released to the public domain"
__author__ = "Doug Fort"
__version__ = 0, 0, 1

import os
import stat
import glob

def dirWalker(top):
    """
    a generator that walks a directory tree

    This code is based on os.path.walk, with the callback function
    replaced by a yield and recursion replaced by crude iteration
    """
    dirstack = [top]
    while len(dirstack) > 0:
        top = dirstack.pop()
        try:
            names = os.listdir(top)
        except os.error:
             return
        yield top, names
        for name in names:
            name = os.path.join(top, name)
            try:
                st = os.lstat(name)
            except os.error:
                 continue
            if stat.S_ISDIR(st[stat.ST_MODE]):
                dirstack.append(name)

def fileWalker(top, pattern):
    """
    a generator to return all files in a directory tree
    whose names match a (glob) pattern.

    for example: '*.py' should find all python scripts 

    pattern a valid argument to glob
    """
    walker = dirWalker(top)
    for dirname, dircontent in walker:
        dirpattern = os.path.join(dirname, pattern)
        for fullname in filter(os.path.isfile, glob.glob(dirpattern)):
            yield fullname

if __name__ == "__main__":
    """test driver -- looks for a starting dir in sys.args[1]"""
    import sys

    walker = dirWalker(sys.argv[1])
    for dirname, dircontent in walker:
        print dirname

    print "filewalker"
    walker = fileWalker(sys.argv[1], "*.py")
    for filename in walker:
        print filename


-- 
Doug Fort, Programmer
http:/www.dougfort.net




More information about the Python-list mailing list