在Python中生成HTML目录树 [英] Generate an HTML directory tree in Python

查看:127
本文介绍了在Python中生成HTML目录树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道我可以将目录路径转换为树的方法,如下(使用Python 2.7)...

does anyone know of a way I can turn a directory path into a tree as follows (using Python 2.7)...

<div>
    <p class="toggle">item one</p>
    <div class="child">

        <p>contained</p>

        <p class="toggle">item</p>
        <div class="child" hidden="true">
            <p>inner</p>
        </div>

        <p class="toggle">item</p>
        <div class="child" hidden="true">
            <p>inner</p>

            <p class="toggle">wow</p>
            <div class="child" hidden="true">
                <p>waaay down</p>
                <p>somefile.py</p>
            </div>

        </div>

        <p class="toggle">item</p>
        <div class="child" hidden="true">
            <p>inner</p>
        </div>

    </div>
</div>

修改:创建上述输出的目录如下所示:

the directory that would create the above output would look like this...

item one
-contained
-item
--inner
-item
--inner
--wow
---waaay down
---somefile.py
-item
--inner

目录需要具有"toggle"类,并且后面应有一个包含该目录内容的div.

Directories need to have the "toggle" class, and should be followed by a div containing the contents of that directory.

如果有人能弄清楚这一点,那就太好了,谢谢!我一直试图弄清楚这一点.

If anyone can figure this out, that would be great, thanks! I've been trying to figure this out for ages.

推荐答案

所以...我想通了!递归函数就是答案.代码在下面

So... I figured it out! Recursive functions are the answer. The code is below

def generate_tree(path, html=""):
    for file in os.listdir(path):
        rel = path + "/" + file
        if os.path.isdir(rel):
            html += "<p class='toggle'>%s</p><div class='child' hidden='true'>" % (file)
            html += generate_tree(rel)
            html += "</div>"
        else:
            html += "<p>%s</p>" % (file)
    return html

这篇关于在Python中生成HTML目录树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆