PythonGenerator

Aus Info-Theke
Zur Navigation springen Zur Suche springen

Example for a Recursive Generator

"""filetree.py:
Implements a generator (iterator) for file trees.
"""
import os
import os.path
import re
import sys

class DirTree:
    def __init__(self, path):
        self._path = path
        
    def next():
        self.traverse(self._path)
        
    def traverse(path):
        for file in os.listdir:
            yield path + "/" + file
        
        for file in os.listdir:
            if file != "." and file != "..":
                full = path + "/" + file
                if os.path.isdir(full):
                    self.traverse(full)
        
def main(argv):
    aDir = DirTree("/etc")
    for full in aDir.next():
        print(full)

if __name__ == "__main__" :
    main(sys.argv)