pythondirectory-walk

A Python walker that can ignore directories


I need a file system walker that I could instruct to ignore traversing directories that I want to leave untouched, including all subdirectories below that branch. The os.walk and os.path.walk just don't do it.


Solution

  • So I made this home-roles walker function:

    import os
    from os.path import join, isdir, islink, isfile
    
    def mywalk(top, topdown=True, onerror=None, ignore_list=('.ignore',)):
        try:
            # Note that listdir and error are globals in this module due
            # to earlier import-*.
            names = os.listdir(top)
        except Exception, err:
            if onerror is not None:
                onerror(err)
            return
        if len([1 for x in names if x in ignore_list]):
            return 
        dirs, nondirs = [], []
        for name in names:
            if isdir(join(top, name)):
                dirs.append(name)
            else:
                nondirs.append(name)
    
        if topdown:
            yield top, dirs, nondirs
        for name in dirs:
            path = join(top, name)
            if not islink(path): 
                for x in mywalk(path, topdown, onerror, ignore_list):
                    yield x
        if not topdown:
            yield top, dirs, nondirs