Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Python生成html目录列表_Python_Html_Flask_Jinja2 - Fatal编程技术网

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

如何使用Python生成html目录列表,python,html,flask,jinja2,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>{}&

我在使用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>')
def列表_文件(起始路径):
对于os.walk(startpath)中的根目录、目录和文件:
级别=根目录。替换(起始路径“”)。计数(os.sep)
如果级别为0:
打印('
  • {}
  • '.format(f)) 其他: 打印('
  • {}
  • '.格式(f)) 打印(“
”)
如果只有根目录、一级子目录和文件,那么它似乎工作得很好。但是,添加另一级别的子目录会导致出现问题(我认为,因为close标记在最后输入的次数不够)。但我很难理解它


如果不能这样做,有没有更简单的方法?我正在使用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的循环<代码>递归功能:

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

值得注意的是,如果您不熟悉Jinja,
dirtree.html
模板文件需要位于名为
templates
@HEADLESS\u 0NE的目录中:我已经明确提到了dirtree.html的放置位置。
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)