title: Python file parsing: Build tree from text file
body: <p>I have an indented text file that will be used to build a tree. Each line represents a node, and indents represent depth as well as node the current node is a child of.</p>
  <p>For example, a file might look like</p>
  <pre>
  ROOT
     Node1
        Node2
           Node3
              Node4
     Node5
     Node6
  </pre>
  <p>Which indicates that ROOT contains three children: 1, 5, and 6, Node1 has one child: 2, and Node2 has one child: 3, etc.</p>
  <p>I have come up with a recursive algorithm and have programmed it and it works, but it's kind of ugly and especially treats the example above very crudely (when going from node 4 to node 5)</p>
  <p>It uses &quot;indent count&quot; as the basis for recursion, so if the number of indents = current depth + 1, I would go one level deeper. But this means when I read a line with less indents, I have to come back up one level at a time, checking the depth each time.</p>
  <p>Here is what I have</p>
  <pre><code>def _recurse_tree(node, parent, depth):
      tabs = 0
      
      while node:
          tabs = node.count(&quot;\t&quot;)
          if tabs == depth:
              print &quot;%s: %s&quot; %(parent.strip(), node.strip())
          elif tabs == depth + 1:
              node = _recurse_tree(node, prev, depth+1)
              tabs = node.count(&quot;\t&quot;)
              
              #check if we have to surface some more
              if tabs == depth:
                  print &quot;%s: %s&quot; %(parent.strip(), node.strip())
              else:
                  return node
          else:
              return node
          
          prev = node
          node = inFile.readline().rstrip()
          
  inFile = open(&quot;test.txt&quot;)
  root = inFile.readline().rstrip()
  node = inFile.readline().rstrip()
  _recurse_tree(node, root, 1)
  </code></pre>
  <p>Right now I am just printing out the nodes to verify that the parent node is correct for each line, but maybe there is a cleaner way to do it? Especially the case in the elif block when I'm coming back from each recursion call.</p>