title: rename file only in specific subfolder with python
body: <p>I've got a path with multiple folders each beginning with 'P' and ending with an individual number ('P001'-'P104'). Each of those folders has two subfolders 'subfolder1' and 'subfolder2' both containing &quot;file_1.nii&quot; and &quot;file_2.nii&quot;. I want to rename &quot;file_1.nii&quot; into &quot;new_name.nii&quot; only in subfolder1, but not in subfolder2.</p>
  <p>This code works for renaming files in all the subfolders:</p>
  <pre><code>import os
  
  mainpath = 'M:/path'
  
  def replace(folder_path, old, new):
     for path, subdirs, files in os.walk(folder_path):
         for name in files: 
             if(old.lower() in name.lower()):
                file_path = os.path.join(path, name)
                new_name = os.path.join(path, name.lower().replace(old,new))
                os.rename(file_path, new_name)
  
  replace(mainpath, 'file_1.nii', 'new_name.nii')
  </code></pre>
  <p>but it would rename 'file_1.nii' in all subfolders. Does anyone know how to extend the code, so it does only rename the file in a specific subfolder or does anyone know an alternative solution?</p>
  <p>TIA!</p>