python - Does os.walk() use recursion or iteration? -


this question has answer here:

okay have seen people os.walk() in python uses recursion , uses iteration. correct answer?

from winpython-64bit-3.5.1.3 ~/lib/os.py... it's recursive

def walk(top, topdown=true, onerror=none, followlinks=false):      dirs = []     nondirs = []      # may not have read permission top, in case can't     # list of files directory contains.  os.walk     # suppressed exception then, rather blow     # minor reason when (say) thousand readable directories still     # left visit.  logic copied here.     try:         # note scandir global in module due         # earlier import-*.         scandir_it = scandir(top)     except oserror error:         if onerror not none:             onerror(error)         return      while true:         try:             try:                 entry = next(scandir_it)             except stopiteration:                 break         except oserror error:             if onerror not none:                 onerror(error)             return          try:             is_dir = entry.is_dir()         except oserror:             # if is_dir() raises oserror, consider entry not             # directory, same behaviour os.path.isdir().             is_dir = false          if is_dir:             dirs.append(entry.name)         else:             nondirs.append(entry.name)          if not topdown , is_dir:             # bottom-up: recurse sub-directory, exclude symlinks             # directories if followlinks false             if followlinks:                 walk_into = true             else:                 try:                     is_symlink = entry.is_symlink()                 except oserror:                     # if is_symlink() raises oserror, consider                     # entry not symbolic link, same behaviour                     # os.path.islink().                     is_symlink = false                 walk_into = not is_symlink              if walk_into:                 yield walk(entry.path, topdown, onerror, followlinks)      # yield before recursion if going top down     if topdown:         yield top, dirs, nondirs          # recurse sub-directories         islink, join = path.islink, path.join         name in dirs:             new_path = join(top, name)             # issue #23605: os.path.islink() used instead of caching             # entry.is_symlink() result during loop on os.scandir() because             # caller can replace directory entry during "yield"             # above.             if followlinks or not islink(new_path):                 yield walk(new_path, topdown, onerror, followlinks)     else:         # yield after recursion if going bottom         yield top, dirs, nondirs 

see yield walk(... statement


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -