title: How to rename files using os.walk()?
body: <p>I'm trying to rename a number of files stored within subdirectories by removing the last four characters in their basename. I normally use <a href="https://docs.python.org/3/library/glob.html#glob.glob" rel="nofollow noreferrer"><code>glob.glob()</code></a> to locate and rename files in <strong>one directory</strong> using:</p>
  
  <pre><code>import glob, os
  
  for file in glob.glob("C:/Users/username/Desktop/Original data/" + "*.*"):
      pieces = list(os.path.splitext(file))
      pieces[0] = pieces[0][:-4]
      newFile = "".join(pieces)       
      os.rename(file,newFile)
  </code></pre>
  
  <p>But now I want to repeat the above in all subdirectories. I tried using <a href="https://docs.python.org/3/library/os.html#os.walk" rel="nofollow noreferrer"><code>os.walk()</code></a>:</p>
  
  <pre><code>import os
  
  for subdir, dirs, files in os.walk("C:/Users/username/Desktop/Original data/"):
      for file in files:
          pieces = list(os.path.splitext(file))
          pieces[0] = pieces[0][:-4]
          newFile = "".join(pieces)       
          # print "Original filename: " + file, " || New filename: " + newFile
          os.rename(file,newFile)
  </code></pre>
  
  <hr>
  
  <p>The <code>print</code> statement correctly prints the original and the new filenames that I am looking for but <code>os.rename(file,newFile)</code> returns the following error:</p>
  
  <pre><code>Traceback (most recent call last):
    File "&lt;input&gt;", line 7, in &lt;module&gt;
  WindowsError: [Error 2] The system cannot find the file specified
  </code></pre>
  
  <p>How could I resolve this?</p>