Python Forum
file tree walk depth first generator
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
file tree walk depth first generator
#1
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)
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  file tree recursion generator Skaperen 7 5,231 Jun-19-2020, 11:07 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020