Jan-10-2018, 10:45 PM
(This post was last modified: Jan-10-2018, 10:45 PM by Gribouillis.)
(Jan-10-2018, 05:54 AM)Skaperen Wrote: here are 2 commands on one line to make a tree and a 2 command pipeline to show the order i want my generator to yield results
os.walk()
cannot do that because it only walks directories, not files.I once wrote a nice generic non-recursive tree/graph traversal module named
walktree
. Using this module, it is a piece of cake to code your traversalfrom collections import namedtuple from walktree import walk import os Node = namedtuple('Node', 'path isdir') def subn(node): if not node.isdir: return () pairs = sorted((e.path, e.is_dir(follow_symlinks=False)) for e in os.scandir(node.path)) return (Node(*p) for p in pairs) def flatwalk(path): root = Node(path, os.path.isdir(path) and not os.path.islink(path)) for seq in walk(root, subn, walk.enter | walk.leaf): yield(seq[-1].path) if __name__ == '__main__': for x in flatwalk('tryme'): print(x)Remark: this code uses scandir() as recommended by G van Rossum.