python - 如何使用 Python 生成 html 目录列表

标签 python html flask jinja2

我在使用 Python 生成 html 文档时遇到了一些问题。我正在尝试创建目录树的 HTML 列表。这是我目前所拥有的:

def list_files(startpath):
    for root, dirs, files in os.walk(startpath):
        level = root.replace(startpath, '').count(os.sep)
        if level <= 1:
            print('<li>{}<ul>'.format(os.path.basename(root)))
        else:
            print('<li>{}'.format(os.path.basename(root)))
        for f in files:
            last_file = len(files)-1
            if f == files[last_file]:
                print('<li>{}</li></ul>'.format(f))
            elif f == files[0] and level-1 > 0:
                print('<ul><li>{}</li>'.format(f))
            else:
                print('<li>{}</li>'.format(f))
    print('</li></ul>')

如果只有根目录,一级子目录和文件,似乎效果很好。但是,添加另一级子目录会导致出现问题(因为我认为最后关闭标签的输入次数不足)。但是我很难理解它。

如果不能这样做,有没有更简单的方法?我正在使用 Flask,但我对模板非常缺乏经验,所以也许我遗漏了一些东西。

最佳答案

您可以将目录树的生成和呈现为 html 分开。

要生成树,您可以使用简单的递归函数:

def make_tree(path):
    tree = dict(name=os.path.basename(path), children=[])
    try: lst = os.listdir(path)
    except OSError:
        pass #ignore errors
    else:
        for name in lst:
            fn = os.path.join(path, name)
            if os.path.isdir(fn):
                tree['children'].append(make_tree(fn))
            else:
                tree['children'].append(dict(name=name))
    return tree

要将其呈现为 html,您可以使用 jinja2 的循环 recursive 功能:

<!doctype html>
<title>Path: {{ tree.name }}</title>
<h1>{{ tree.name }}</h1>
<ul>
{%- for item in tree.children recursive %}
    <li>{{ item.name }}
    {%- if item.children -%}
        <ul>{{ loop(item.children) }}</ul>
    {%- endif %}</li>
{%- endfor %}
</ul>

将 html 放入 templates/dirtree.html 文件中。 要对其进行测试,请运行以下代码并访问 http://localhost:8888/:

import os
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def dirtree():
    path = os.path.expanduser(u'~')
    return render_template('dirtree.html', tree=make_tree(path))

if __name__=="__main__":
    app.run(host='localhost', port=8888, debug=True)

关于python - 如何使用 Python 生成 html 目录列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10961378/

相关文章:

python - None 的 numpy 索引切片

python - 什么时候使用 Python 特殊方法?

python - 用于 bbcode 输入的自定义 django 管理表单

html - 如何仅对元素使用文本缩进而不是 :before Selector?

python - 将一个函数插入到 Flask 中的多个蓝图中

python - 如何使用atom-ide-debugger-python来调试python代码,包括。变量监视和断点

javascript - 通过模板输出时Python字典对象转换为JSON

python - 在给定到达和离开时间矩阵的情况下,想出给定时间排队的人数?

javascript - 计算所有浏览器中元素的绘制时间

html - 如何根据 BeautifulSoup 的特定链接抓取文本?