Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8051515
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T07:19:13+00:00 2026-06-05T07:19:13+00:00

I am having some problems using Python to generate an html document. I am

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T07:19:14+00:00Added an answer on June 5, 2026 at 7:19 am

    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)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm having some problems using cascade operations on hibernate. I have one entity (TripleDBmodel),
I am having some problems parsing this piece of XML using SimpleXML. There is
I am having some problems with processing my form in python django when using
Im having some problems with redirections. Im using primefaces and JSF 2.1. The thing
I'm having some problems adding a dropdownlist with ajax and stuff using jQuery. When
I'm having some problems with users cheating my online game by using macros to
I am using the jQuery UI components but having some problems. If I try
I'm making some tests using threads in Perl 5.10.1 but I'm having some problems.
I'm having troubles getting this to work. Basically I have a python program that
I've recently been having some problems with my imports in Django (Python)... It's better

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.