PythonGenerator

Aus Info-Theke
Version vom 25. August 2016, 10:03 Uhr von 212.144.248.2 (Diskussion) (Die Seite wurde neu angelegt: „Kategorie:Python == Example for a Recursive Generator == <pre>"""filetree.py: Implements a generator (iterator) for file trees. """ import os import os.pat…“)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
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)