title: Renaming files that contain a pattern, looping through subfolders
body: <p>I have a main folder, that contains multiple subfolders, that contain multiple files. I am trying to loop through subfolders and rename files that match a certain pattern. Here is what I have:</p>
  <pre><code>import os
  from fnmatch import fnmatch
  
  pattern = &quot;*z_2*&quot;
  pattern2 ='b_2.txt'
  path = r'C:\Users\Desktop\123'
  list1= []
  
  for (dirpath, dirnames, filenames) in os.walk(path):
      list1+= [os.path.join(dirpath, file) for file in filenames]
      for i in list1:
          if fnmatch(i,pattern):
              a=os.path.join(path,i)
              b = os.path.dirname(i)
              os.rename(a, os.path.join(b,pattern2))
  </code></pre>
  <p>What I don't understand, is why, when I specify use os.<strong>rename</strong> , it is instead creating a text file in the specified subfolder, resulting in:</p>
  <pre><code>FileExistsError: [WinError 183] Cannot create a file when that file already exists: 'C:\\Users\\Desktop\\ABC\\_100\\az_207.txt' -&gt; 'C:\\Users\\Desktop\\ABC\\_100\\b_2.txt'
  </code></pre>