title: Getting a File System Listing Python
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/7478477/create-a-tree-style-directory-listing-in-python">Create a tree-style directory listing in Python</a>  </p>
  </blockquote>
  
  
  
  <p>I would like to analyze the file system and print the result as formatted file. My first implementation can simply be plain text, but at a later date I would like to incorporate HTML.</p>
  
  <p>I am using a basic method to gather the files contained within each folder, which I can return and send to the text processor:</p>
  
  <pre><code>def gather_tree(source):
          tree = {}
          for path, dirs, files in os.walk(source):
              tree[path] = []
              for file in files:
                  tree[path].append(file)
          return tree
  </code></pre>
  
  <p>Clearly, the problem here is that I am producing a structure that has no concept of depth which I guess I need to be able to correctly format the list with adequate space and nesting.</p>
  
  <p>My currently very basic print pattern looks like this:</p>
  
  <pre><code>def print_file_tree(tree):
      # Prepare tree
      dir_list = tree.keys()
      dir_list.sort()
  
      for directory in dir_list:
          print directory
          for f in tree[directory]:
              print f
  </code></pre>
  
  <p>I am kind new to data structures and would appreciate some input!</p>