# Yield before sub-directory traversal if going top down
yield top, dirs, nondirs
# Traverse into sub-directories
- for dirname in reversed(dirs):
- new_path = join(top, dirname)
- # bpo-23605: os.path.islink() is used instead of caching
- # entry.is_symlink() result during the loop on os.scandir() because
- # the caller can replace the directory entry during the "yield"
- # above.
- if followlinks or not islink(new_path):
- stack.append(new_path)
+ if dirs:
+ prefix = join(top, top[:0]) # Add trailing slash
+ for dirname in reversed(dirs):
+ new_path = prefix + dirname
+ # bpo-23605: os.path.islink() is used instead of caching
+ # entry.is_symlink() result during the loop on os.scandir() because
+ # the caller can replace the directory entry during the "yield"
+ # above.
+ if followlinks or not islink(new_path):
+ stack.append(new_path)
else:
# Yield after sub-directory traversal if going bottom up
stack.append((top, dirs, nondirs))