#### Source code for ./examples/walk.py ####
#!/usr/bin/env python
"""my first sysadmin module
starting with a function to walk directories
"""
# *****************************************************************************
from __future__ import generators
import sys
import os
import stat
# *****************************************************************************
def walktree(top='.', depthfirst=True, ):
"""Directory tree generator.
Traverses filesystem from directory 'top' downwards, returning each
directory found and a list of files in that directory.
If depthfirst is True, returns files found from bottom of tree first.
See also os.walk, available in Python 2.3 on.
Thanks to Noah Spurrier and Doug Fort.
"""
names = os.listdir(top)
if not depthfirst:
yield top, names
for name in names:
try:
state = os.lstat(os.path.join(top, name))
except os.error:
continue
if stat.S_ISDIR(state.st_mode):
for (newtop, children)in \
walktree(os.path.join(top, name), depthfirst):
yield newtop, children
if depthfirst:
yield top, names
# *****************************************************************************
if __name__ == '__main__':
sys.stdout.write('Enter directory to walk >> ')
root = sys.stdin.readline().strip()
sys.stdout.write('\n')
if not root:
sys.exit()
sys.stdout.write('Depth first [y|n] [y] ? >> ')
df = (sys.stdin.readline().upper().strip()in ('Y', '', ))
sys.stdout.write('\n')
for basepath, children in walktree(top = root, depthfirst = df, ):
sys.stdout.write('%s\n'%basepath)
for child in children:
sys.stdout.write('\t%s\n'%child)
print root, df
# *****************************************************************************
[Created with py2html Ver:0.62]