python按模板生成html,如何使用Python生成html目录列表

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

{}
  • '.format(os.path.basename(root)))

else:

print('

{}'.format(os.path.basename(root)))

for f in files:

last_file = len(files)-1

if f == files[last_file]:

print('

{}'.format(f))

elif f == files[0] and level-1 > 0:

print('

  • {}'.format(f))

else:

print('

{}'.format(f))

print('

')

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:

Path: {{ tree.name }}

{{ tree.name }}

{%- for item in tree.children recursive %}

{{ item.name }}

{%- if item.children -%}

  • {{ loop(item.children) }}

{%- endif %}

{%- endfor %}

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值