PythonGenerator

Aus Info-Theke
Version vom 25. August 2016, 10:23 Uhr von 212.144.248.2 (Diskussion) (→‎Example for a Recursive Generator)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
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)