Welcome, guest | Sign In | My Account | Store | Cart

This is a new implementation of directory walking inspired by Fredrik Lundh's directoryWalker.py (see http://aspn.activestate.com/ASPN/Mail/Message/541112 ). This code uses a generator instead of a class, so it requires Python 2.2 or above.

Python, 13 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from __future__ import generators

import os

def dirwalk(dir):
    "walk a directory tree, using a generator"
    for f in os.listdir(dir):
        fullpath = os.path.join(dir,f)
        if os.path.isdir(fullpath) and not os.path.islink(fullpath):
            for x in dirwalk(fullpath):  # recurse into subdir
                yield x
        else:
            yield fullpath

Compare this code to the original directoryWalker.py code at http://aspn.activestate.com/ASPN/Mail/Message/541112. By using a recursive generator the concept may be expressed more concisely. (Requires Python 2.2 or above)

6 comments

Tom Good (author) 22 years, 2 months ago  # | flag

oops - typo. there is a typo in the listing, the line that says "for x in directoryWalk(fullpath):" should say "for x in dirwalk(fullpath):"

Tom Good (author) 22 years, 2 months ago  # | flag

fixed the typo mentioned above

Robin Siebler 21 years, 8 months ago  # | flag

How would I use this? I'm new to Python. Can you give an example of how to use this?

Stefano Spinucci 21 years, 4 months ago  # | flag

Example of use. If you want to list the content of the directory "c:\python22" you can use the following code :

for elem in dirwalk("c:\python22"):
        print elem
Bob Costello 17 years, 4 months ago  # | flag

Empty directory paths? Is there a way for this to also yield empty directory paths?

Bob Costello 17 years, 4 months ago  # | flag

Now gives empty directories! I've answered my own request...

def dirwalk(dir, giveDirs=0):
    """
    walk a directory tree, using a generator
    """
    import os

    for f in os.listdir(dir):
        fullpath = os.path.join(dir,f)
        if os.path.isdir(fullpath) and not os.path.islink(fullpath):
            if not len(os.listdir(fullpath)):
                yield fullpath + os.sep
            else:
                for x in dirwalk(fullpath):  # recurse into subdir
                    if os.path.isdir(x):
                        if giveDirs:
                            yield x
                    else:
                        yield x
        else:
            yield fullpath
Created by Tom Good on Fri, 4 Jan 2002 (PSF)
Python recipes (4591)
Tom Good's recipes (4)

Required Modules

Other Information and Tasks