【问题标题】:Generate an HTML directory tree in Python在 Python 中生成 HTML 目录树
【发布时间】:2017-04-28 02:10:46
【问题描述】:

有谁知道我可以将目录路径转换为树的方法,如下所示(使用 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>

编辑: 将创建上述输出的目录如下所示...

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

目录需要有“toggle”类,并且后面应该有一个包含该目录内容的 div。

如果有人能解决这个问题,那就太好了,谢谢!多年来我一直在尝试解决这个问题。

【问题讨论】:

  • 您应该编辑此问题以显示输入目录结构以与您的输出一起使用,以便清楚地了解程序需要做什么。
  • @mVChr 感谢您指出这一点!

标签: python html tree directory


【解决方案1】:

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

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中的保留关键字吗?
  • 另外,第三行可以换成这样,使其更适合跨平台:rel = os.path.join(folder, filename)
猜你喜欢
  • 2010-10-05
  • 2019-06-24
  • 2021-02-17
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多