pythonic tree-walking idioms

Neil Schemenauer nas at python.ca
Thu May 17 22:00:57 EDT 2001


Fredrik Lundh wrote:
> (chances are that Python 2.2 will provide a better iterator inter-
> face, which makes this a bit more efficient.  see PEP 234 for more
> info [2]).

Here's something that works with my generators:

    import os

    def walk(directory):
        stack = [directory]
        while stack:
            directory = stack.pop()
            for file in os.listdir(directory):
                fullname = os.path.join(directory, file)
                if os.path.isdir(fullname) and not os.path.islink(fullname):
                    stack.append(fullname)
                yield fullname

Its also easy to build on.  Here's a generator that works a bit
like the find command.

    import fnmatch

    def find(directory, pat):
        for file in walk(directory):
            if fnmatch.fnmatch(file, pat):
                yield file

    # find all the Python sources in the current directory
    for file in find(".", "*.py"):
        print file


If your curious about generators and iterators most of the
discussion seems to be occuring on the SF mailing list¹.

  Neil


¹ python-iterators at lists.sourceforge.net




More information about the Python-list mailing list