title: Python - loop through subfolders and files in a directory without ignoring the subfolder
body: <p>I have read all the stack exchange help files on looping through subfolders, as as well as the os documentation, but I am still stuck. I am trying to loop over files in subfolders, open each file, extract the first number in the first line, copy the file to a different subfolder(with the same name but in the output directory) and rename the file copy with the number as a suffix. </p>
  
  <pre><code>import os
  import re
  outputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/Wisconsin_Copies_With_PageNumbers"
  inputpath = "C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/FRUS_Wisconsin"
  suffix=".txt" 
  for root, dirs, files  in os.walk(inputpath):
      for file in files:
          file_path = os.path.join(root, file)
          foldername=os.path.split(os.path.dirname(file_path))[1]
          filebname=os.path.splitext(file)[0]
          filename=filebname + "_"
          f=open(os.path.join(root,file),'r')
          data=f.readlines()
          if data is None:
              f.close() 
          else:
              with open(os.path.join(root,file),'r') as f:
                  for line in f:
                      s=re.search(r'\d+',line)
                      if s:
                          pagenum=(s.group())
                          break
          with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
              with open(os.path.join(root,file),'r') as f:
                  for line in f:
                      f1.write(line)
  </code></pre>
  
  <p>I expect the result to be copies of the files in the input directory placed in the corresponding subfolder in the output directory, renamed with a suffix, such as "005_2", where 005 is the original file name, and 2 is the number the python code extracted from it. </p>
  
  <p>The error I get seems to indicates that I am not looping through files correctly. I know the code for extracting the first number and renaming the file works because I tested it on a single file. But using os.walk to loop through multiple subfolders is not working, and I can't figure out what I am doing wrong. Here is the error:</p>
  
  <pre><code>File "&lt;ipython-input-1-614e2851f16a&gt;", line 23, in &lt;module&gt;
      with open(os.path.join(outputpath, foldername,filename+pagenum+suffix), 'w') as f1:
  IOError: [Errno 2] No such file or directory: 'C:/Users/Heather/Dropbox/T_Files/Raw_FRUS_Data/Wisconsin_Copies_With_PageNumbers\\FRUS_Wisconsin\\.dropbox_1473986809.txt'
  </code></pre>