如何使用Python生成html目录列表 [英] How to generate an html directory list using Python

查看:396
本文介绍了如何使用Python生成html目录列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些使用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>格式(os.path.basename(root)))
else:
print('< li> {}'。format(os.path.basename(root )))
for file in:
last_file = len(files)-1
if f == files [last_file]:
print('< li> {} < / ul>'。format(f))
elif f == files [0] and level-1>格式(f))
print('< ul>< li> {}< / li>'
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)
除了OSError:
pass #ignore错误
else:
在lst中的名字:
fn = os.path.join(path,name)
如果os.path.isdir(fn):
tree ['children']。append(make_tree(fn))
else:$ b $ tree ['children']。append (dict(name = name))
返回树

使用jinja2循环递归特性:

 <!doctype html> 
< title>路径:{{tree.name}}< / title>
< h1> {{tree.name}}< / h1>
< ul>
{% - for tree.children递归%}
< li> {{item.name}}
{% - if item.children - %}
< ; ul> {{loop(item.children)}}< / ul>
{% - endif%}< / li>
{% - endfor%}
< / ul>

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

 def dirtree():
path = os.path.expanduser(u'〜')
return render_template('dirtree.html',tree = make_tree(path))
$ b $ if if __name __ ==__ main__:
app.run(host ='localhost',port = 8888,debug = True)
pre>

I am having some problems using Python to generate an html document. I am attempting to create an HTML list of a directory tree. This is what I have so far:

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>')

It seems to work well if there is only the root directory, one level of sub-directories and files. However, adding another level of sub-directories causes there to be problems (because the close tag isn't input enough times at the end I think). But I'm having a hard time getting my head around it.

If it can't be done this way, is there an easier way to do it? I'm using Flask but I'm very inexperienced with templates so perhaps I'm missing something.

解决方案

You could separate the directory tree generation and its rendering as html.

To generate the tree you could use a simple recursive function:

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

To render it as html you could use jinja2's loop recursive feature:

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

Put the html into templates/dirtree.html file. To test it, run the following code and visit 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生成html目录列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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