1

does anyone know of a way I can turn a directory path into a tree as follows (using Python 2.7)...

<div>
    <p class="toggle">item one</p>
    <div class="child">

        <p>contained</p>

        <p class="toggle">item</p>
        <div class="child" hidden="true">
            <p>inner</p>
        </div>

        <p class="toggle">item</p>
        <div class="child" hidden="true">
            <p>inner</p>

            <p class="toggle">wow</p>
            <div class="child" hidden="true">
                <p>waaay down</p>
                <p>somefile.py</p>
            </div>

        </div>

        <p class="toggle">item</p>
        <div class="child" hidden="true">
            <p>inner</p>
        </div>

    </div>
</div>

Edit: the directory that would create the above output would look like this...

item one
-contained
-item
--inner
-item
--inner
--wow
---waaay down
---somefile.py
-item
--inner

Directories need to have the "toggle" class, and should be followed by a div containing the contents of that directory.

If anyone can figure this out, that would be great, thanks! I've been trying to figure this out for ages.

1
  • 1
    You should edit this question to show the input directory structure to go along with your output so that it's clear exactly what the program needs to do. Commented Dec 13, 2016 at 4:56

1 Answer 1

2

So... I figured it out! Recursive functions are the answer. The code is below

def generate_tree(path, html=""):
    for file in os.listdir(path):
        rel = path + "/" + file
        if os.path.isdir(rel):
            html += "<p class='toggle'>%s</p><div class='child' hidden='true'>" % (file)
            html += generate_tree(rel)
            html += "</div>"
        else:
            html += "<p>%s</p>" % (file)
    return html
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't "file" supposed to be a reserved keyword in python?
Also, the third line can be replaced with this to make it more cross-platform friendly: rel = os.path.join(folder, filename)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.