Generate an HTML directory tree in Python

折月煮酒 提交于 2021-02-08 07:52:42

问题


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>

Edit: 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

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.


回答1:


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


来源:https://stackoverflow.com/questions/41113929/generate-an-html-directory-tree-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!