title: Recursive printing of file directory in Python
body: <p>I'm trying to figure out how to print out each item in a directory with proper indentation. The code I have so far is below:</p>
  
  <pre><code>import os
  
  def traverse(pathname,d):
      'prints a given nested directory with proper indentation'
      indent = ''
      for i in range(d):
          indent = indent + '  '
      for item in os.listdir(pathname):
          try:
              newItem = os.path.join(pathname, item)
              traverse(newItem,d+1)
          except:
              print(indent + newItem)
  </code></pre>
  
  <p>The output that I have prints out all the files in the test directory, but does not print out the folder names. What I get is this:</p>
  
  <pre><code>&gt;&gt;&gt; traverse('test',0)
  test/fileA.txt
    test/folder1/fileB.txt
    test/folder1/fileC.txt
      test/folder1/folder11/fileD.txt
    test/folder2/fileD.txt
    test/folder2/fileE.txt
  &gt;&gt;&gt;
  </code></pre>
  
  <p>What the output should be:</p>
  
  <pre><code>&gt;&gt;&gt; traverse('test',0)
  test/fileA.txt
  test/folder1
    test/folder1/fileB.txt
    test/folder1/fileC.txt
    test/folder1/folder11
      test/folder1/folder11/fileD.txt
  test/folder2
    test/folder2/fileD.txt
    test/folder2/fileE.txt
  &gt;&gt;&gt;
  </code></pre>
  
  <p>Can anyone let me know what I need to be doing with the code to get the folder names to show up? I've tried to print out the pathname, but it just repeats the folder name every time Python prints out a file name since it is in a for loop. A nudge in the right direction would be greatly appreciated!</p>