English 中文(简体)
• 如何将 director树作为超文本生产?
原标题: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))

基本上,我想做的是把我的项目目录结构与所有XML文件作为超文本树木(使用<代码>和t;ul>)。 我可以这样获得所有档案,但我似乎无法说明如何把档案整理成树。

<代码>s.walk 我不知道我何时走过更深的层次,或者如果我仍然拿着同一个目录。


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> )  

这使我有一份目录和所有档案都附在后面,但我仍然能够说明如何分拨目录,以便把目录放在一边。

最佳回答

<代码>.walk, 如果你注意等级划分,可能不是最佳解决办法。 较为简单的解决办法可能只是使用os.listdir,加上os.path.isdir,以 rec取回你的树木。

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)
问题回答

你们需要重新接触。 作为起点:

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>
<li>" + tmp[-1] + "</li>"
    elif len(tmp)==len(tmpold):
        print "<li>" + tmp[-1] + "</li>"
    else:
        print "</ul>
"*(1+len(tmpold)-len(tmp)) + "<ul>
<li>" + tmp[-1] + "</li>"
    tmpold = tmp

然而,正如其他发言者提到的那样,每个(次)文件夹都需要一个手法的复读解决办法,可以简化你的任务。

这是自提出这一问题以来的一分钟,但我最近需要的是类似的东西,而<>特里·<>/代码>的制定者(吗?)使其非常容易。

    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> )




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签