title: python3: having problems with os.walk
body: <p>I have the following directory/file setup (this is simplified):</p>
  
  <pre><code>Ce  
  +---top.txt
  +---X0.0        
  |     |  
  |     +---Y0.0  
  |     |     |
  |     |     +---X0.0Y0.0Z0.0.dat
  |     |     +---X0.0Y0.0Z0.05.dat   
  |     +---Y0.05
  |           |
  |           +---X0.0Y0.05Z0.0.dat
  |           +---X0.0Y0.05Z0.05.dat
  +---X0.05
        |  
        +---Y0.0  
        |     |
        |     +---X0.0Y0.0Z0.0.dat
        |     +---X0.0Y0.0Z0.05.dat   
        +---Y0.05
              |
              +---X0.0Y0.05Z0.0.dat
              +---X0.0Y0.05Z0.05.dat
  </code></pre>
  
  <p>Within each Y directory, I need to make a 'psub' file, which contains appends a list of the .dat files to a copy of the file 'top.txt'.</p>
  
  <p>I am attempting to do this using the os.walk function in python 3: however I am incurring two problems:<br>
  1. The new psub file appears in the X0.0 directory<br>
  2. Code does not list any filenames (presumably because it is not finding any) and then gives the error that it is unable to find the X0.05 directory. </p>
  
  <p>Thus far, I have the following code:</p>
  
  <pre><code>import os
  
  with open('top.txt', 'r') as reader:
      data=reader.read()
      for root, dirs, files in os.walk('.'):
          for folder in dirs:
              os.chdir(os.path.join(root, folder))
              with open('psub', 'a') as writer:
                  writer.write(data)
                  for names in files:
                      if names.endswith('.dat'):
                          print('gulp &lt;' + names + '&gt; ', end='', file=writer)
                          print(names.rsplit('.',1)[0], end='', file=writer)
                          print('.out', file=writer)
  </code></pre>
  
  <p>The resulting psub file should be:  </p>
  
  <pre><code>#!/bin/bash
  #MOAB -l walltime=48:00:0
  #MOAB -j oe
  #MOAB -N GULP-job
  cd "$PBS_O_WORKDIR"
  module load apps/gulp
  #!/bin/bash
  gulp &lt;X0.00Y0.00Z0.00.dat&gt; X0.00Y0.00Z0.00.out
  gulp &lt;X0.00Y0.00Z0.05.dat&gt; X0.00Y0.00Z0.05.out
  </code></pre>
  
  <p>of which the first seven lines are in top.txt. </p>
  
  <p>Any (simple) pointers as to where I am going wrong would be much appreciated.
  Cheers</p>