I needed the pathlib equivalent to os.walk so I went to the source code for os.walk and reimplemented it to use pathlib instead
def path_walk(top, topdown = False, followlinks = False): """ See Python docs for os.walk, exact same behavior but it yields Path() instances instead """ names = list(top.iterdir()) dirs = (node for node in names if node.is_dir() is True) nondirs =(node for node in names if node.is_dir() is False) if topdown: yield top, dirs, nondirs for name in dirs: if followlinks or name.is_symlink() is False: for x in path_walk(name, topdown, followlinks): yield x if topdown is not True: yield top, dirs, nondirs
yes there is Path.glob(“**”) but I like how os.walk is structured and this passes my unit-tests.
dirs and nondirs are generators out of habit. List comprehensions would likely be better and it’s almost impossible to avoid the overhead memory cost so having them as is, is just personal preference.