问题
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:
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
来源:https://stackoverflow.com/questions/41113929/generate-an-html-directory-tree-in-python