A directory tree walker that returns the files in breadth first order
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #!/usr/bin/env python
import os
# -------------------------------------------
def breadthFirstFileScan( root ) :
dirs = [root]
# while we has dirs to scan
while len(dirs) :
nextDirs = []
for parent in dirs :
# scan each dir
for f in os.listdir( parent ) :
# if there is a dir, then save for next ittr
# if it is a file then yield it (we'll return later)
ff = os.path.join( parent, f )
if os.path.isdir( ff ) :
nextDirs.append( ff )
else :
yield ff
# once we've done all the current dirs then
# we set up the next itter as the child dirs
# from the current itter.
dirs = nextDirs
# -------------------------------------------
# an example func that just outputs the files.
def walkbf( path ) :
for f in breadthFirstFileScan( path ) :
print f
# ============================================
# as a demo we'll just start from where we
# were called from.
walkbf( os.getcwd() )
|
this is a example of how easy it is to write and use iterators. in this case a replacement for os.path.walk that does breath first rather than the variants of depth first.
Tags: files
Breadth? Ok, my ignorance is showing. What does this mean in this context?