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.
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)
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):"
fixed the typo mentioned above
How would I use this? I'm new to Python. Can you give an example of how to use this?
Example of use. If you want to list the content of the directory "c:\python22" you can use the following code :
Empty directory paths? Is there a way for this to also yield empty directory paths?
Now gives empty directories! I've answered my own request...