PythonGenerator

Aus Info-Theke
Zur Navigation springen Zur Suche springen

Example for a Recursive Generator[Bearbeiten]

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

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

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