Python Forum
file tree walk depth first generator - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: file tree walk depth first generator (/thread-20456.html)



file tree walk depth first generator - Skaperen - Aug-12-2019

this has only been tested in Python3. it does a file tree walk in depth first. it can take keyword argument key= referring to a function to pass to sorted(key=) to sort file system object names as desired.

def ftrgenk(path,**opts):
    """File tree recursion (ftr) generator that yields all paths, sorted by sortkey via key=."""
    #-------#-------#-------#-------#-------#-------#-------#-------#-------#-
    # Copyright © 2018, 2019, by Phil D. Howard - all other rights reserved
    # 
    # Permission to use, copy, modify, and/or distribute this software for any
    # purpose with or without fee is hereby granted, provided that the above
    # copyright notice and this permission notice appear in all copies.
    # 
    # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
    # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
    # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
    # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
    # WHATSOEVER RESULTING FROM LOSS OF USE, DATA, OR PROFITS, WHETHER IN AN
    # ACTION OF CONTRACT, NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF
    # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
    # 
    # The author may be contacted by decoding the number
    # 11054987560151472272755686915985840251291393453694611309
    # (provu igi la numeron al duuma)
    #-------#-------#-------#-------#-------#-------#-------#-------#-------#-
    from os import listdir,readlink
    from sys import argv,stdout
    kfun = opts.pop('key',None)
    pre = 'TypeError: '+__name__+'() '
    depth = opts.pop('depth',2**62)
    if opts:
        raise TypeError(pre+'got an unexpected keyword argument '+' '.join([repr(x) for x in opts.keys()]))
    if not isinstance(path,str):
        raise TypeError(pre+'apex path is not a string')
    level = [[path]]
    deep = 0
    while level[0]:
        if level[-1]:
            path = '/'.join([x[0] for x in level])
            yield path
            try:
                readlink(path)
                names = []
            except OSError:
                try:
                    names = sorted(listdir(path),key=kfun)
                except OSError:
                    names = []
                deep += 1
                if deep > depth:
                    names = []
            if names:
                level.append(names)
            else:
                level[-1].pop(0)
            continue
        else:
            level[-1:] = []
            level[-1].pop(0)