开发者

How to output a directory tree as HTML?

Here's what I've got so far:

project_dir = '/my/project/dir'
project_depth = len(project_dir.split(os.path.sep))

xml_files = []
for dirpath, dirnames, filenames in os.walk(project_dir):
    for filename in fnmatch.filter(filenames, '*.xml'):
        dirs = dirpath.split(os.path.sep)[project_depth:]
        print(dirs)
        xml_files.append(os.path.join(dirpath,filename))

Essentially what I want to do is spit out my project directory structure with all the XML files as an HTML tree (using <ul>). I can get all the files this way, but I can't seem to figure out how to organize them into a tree.

With the way this os.walk works, I don't know when I've gone in a level deeper, or if I'm still traversing the same directory.


for dirpath, dirnames, filenames in os.walk(project_dir):
    xml_files = fnmatch.filter(filenames, '*.xml')
    if len(xml_files) > 0:
        out.write(开发者_开发问答'<li>{0}<ul>'.format(dirpath))
        for f in xml_files:
            out.write('<li>{0}</li>'.format(f))
        out.write('</ul></li>')
out.write('</ul>')  

This gives me a list of directories and all the files underneath them, but I still can't figure out how to split the directory path so that it's nested too.


os.walk might not be the best solution if you care about the hierarchy. A simpler solution would probably be just do use os.listdir with os.path.isdir to traverse your tree recursively.

import os

def traverse(dir):
    print '<ul>'
    for item in os.listdir(dir):
        print '<li>%s</li>' % item
        fullpath = os.path.join(dir, item)
        if os.path.isdir(fullpath):
            traverse(fullpath)
    print '</ul>'

projectdir = '.'
traverse(projectdir)


You need recursion. As a starting point:

import os

def walk(d, ident=""):
    print "<ul>"
    for p in os.listdir(d):
        fullpath = os.path.join(d, p)
        print ident, "<li>",p,"</li>"
        if os.path.isdir(fullpath):
            walk(fullpath, ident+"   ")
    print "</ul>"

walk(".")


import os

tmpold=[]
for (f, fol, fil) in os.walk("./mydir"):
    tmp = f.split("/")
    if len(tmp)>len(tmpold):
        print "<ul>\n<li>" + tmp[-1] + "</li>"
    elif len(tmp)==len(tmpold):
        print "<li>" + tmp[-1] + "</li>"
    else:
        print "</ul>\n"*(1+len(tmpold)-len(tmp)) + "<ul>\n<li>" + tmp[-1] + "</li>"
    tmpold = tmp

However, as others mentioned, a handcrafted recursive solution that is called for each (sub)folder may simplify your task.


Its been a minute since this question was posed, but I recently needed something similar and the tree developers (??) made it pretty easy.

    tree path_to_directories -H . -o output_filename.html


def buildtree(dir):
    tree = []
    for item in os.listdir(dir):
        path = os.path.join(dir, item)
        if os.path.isdir(path):
            subtree = buildtree(path)
            if len(subtree) > 0:
                tree.append((item,subtree))
        elif item.endswith('.xml'):
            tree.append(item)
    return tree

def writetree(tree, fp):
    fp.write('<ul>')
    for n in tree:
        fp.write('<li>')
        if isinstance(n,tuple):
            fp.write(n[0])
            writetree(n[1],fp)
        else:
            fp.write(n)
        fp.write('</li>')
    fp.write('</ul>')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜