PythonGenerator: Unterschied zwischen den Versionen

Aus Info-Theke
Zur Navigation springen Zur Suche springen
 
Zeile 10: Zeile 10:


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


if __name__ == "__main__" :
if __name__ == "__main__" :
     main(sys.argv)
     main(sys.argv)
</pre>
</pre>

Aktuelle Version vom 25. August 2016, 10:23 Uhr

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)