mit Python Verzeichnisse rekursiv durchsuchen?

vincent wehren v.wehren at home.nl
Wed Mar 26 14:43:19 EST 2003


"Jan van Helsing" <gato at ba-horb.de> schrieb im Newsbeitrag
news:94e97915.0303260811.661189bb at posting.google.com...
> Hallo allerseits!
>
> Ich habe ein Problem - ich will mit einem Python-Skript Verzeichnisse
> rekursiv nach einem bestimmtbaren Dateityp durchsuchen und die
> Ergebnisse nach Verzeichnissen sortiert in eine HTML oder LaTeX Datei
> ausgeben.
> Kann mir jemand helfen? Diese Rekursion ist mir echt zu hoch ;-)


Thought I have a go at the HTML option..
So how about this one ....

HTH,
Vincent Wehren

<code>
import os
global dirs
dirs={}

def treewalker(directory, callback, ftype):

    join = os.path.join
    dirs[directory]=[] #takes care of top directory
    for f in os.listdir(directory):
        pathname = join(directory, f)
        if os.path.isdir(pathname):
            dirs[pathname] = [] #add key
            print "...in %s" % (pathname)
            treewalker(pathname, callback, ftype)
        elif os.path.isfile(pathname) :
            callback(pathname, ftype)

def callback(pathname, ftype):

    dirname = os.path.dirname(pathname)
    if os.path.splitext(pathname)[1] == ftype:
        dirs[dirname].append(os.path.normpath(pathname))


if  __name__ == "__main__":
    import webbrowser
    outfile="output.html"
    top =r"c:\bin"
    suffix = ".py"
    fw = open(outfile, "w")
    treewalker(top, callback, suffix)
    for dir in dirs.keys():
        l = dirs[dir]
        if len(l)>0:
            fw.write("<h3>Directory: %s</h3>\n" % (dir))
            fw.write("  <dir>\n")
            for f in l:
                fw.write( "      <li>%s\n" %  os.path.basename(f))
            fw.write("   </dir>\n")
    fw.close()
    webbrowser.open(outfile)

</code>


>
> Danke im Voraus!






More information about the Python-list mailing list