How to generate an html directory list using Python

前端 未结 1 1494
你的背包
你的背包 2020-12-01 07:00

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:

         


        
1条回答
  •  我在风中等你
    2020-12-01 07:13

    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)
    

    0 讨论(0)
提交回复
热议问题