faqts : Computers : Programming : Languages : Python : Snippets : os.*

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

14 of 15 people (93%) answered Yes
Recently 9 of 10 people (90%) answered Yes

Entry

Alternative to os.path.walk

Sep 25th, 2000 08:31
Daniel Dittmar,


If you have trouble specifying the correct callback to os.path.walk and 
would prefer to use an iterator as in 
for fname in RecursiveFileIterator ('dir1', 'dir2'):
   process (fname)
class RecursiveFileIterator:
    def __init__ (self, *rootDirs):
        self.dirQueue = list (rootDirs)
        self.includeDirs = None
        self.fileQueue = []
    def __getitem__ (self, index):
        while len (self.fileQueue) == 0:
            self.nextDir ()
        result = self.fileQueue [0]
        del self.fileQueue [0]
        return result
    def nextDir (self):
        dir = self.dirQueue [0]   # fails with IndexError, which is fine
                                  # for iterator interface
        del self.dirQueue [0]
        list = os.listdir (dir)
        join = os.path.join
        isdir = os.path.isdir
        for basename in list:
            fullPath = join (dir, basename)
            if isdir (fullPath):
                self.dirQueue.append (fullPath)
                if self.includeDirs:
                    self.fileQueue.append (fullPath)
            else:
                self.fileQueue.append (fullPath)