title: How to generate an html directory list using Python
body: <p>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:</p>
  
  <pre><code>def list_files(startpath):
      for root, dirs, files in os.walk(startpath):
          level = root.replace(startpath, '').count(os.sep)
          if level &lt;= 1:
              print('&lt;li&gt;{}&lt;ul&gt;'.format(os.path.basename(root)))
          else:
              print('&lt;li&gt;{}'.format(os.path.basename(root)))
          for f in files:
              last_file = len(files)-1
              if f == files[last_file]:
                  print('&lt;li&gt;{}&lt;/li&gt;&lt;/ul&gt;'.format(f))
              elif f == files[0] and level-1 &gt; 0:
                  print('&lt;ul&gt;&lt;li&gt;{}&lt;/li&gt;'.format(f))
              else:
                  print('&lt;li&gt;{}&lt;/li&gt;'.format(f))
      print('&lt;/li&gt;&lt;/ul&gt;')
  </code></pre>
  
  <p>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.</p>
  
  <p>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.</p>