title: How to change multiple filenames in a directory using Python
body: <p>I am learning Python and I have been tasked with:</p>
  
  <ul>
  <li>adding "file_" to the beginning of each name in a directory</li>
  <li>changing the extension (directory contains 4 different types currently: .py, .TEXT, .rtf, .text)</li>
  </ul>
  
  <p>I have many files, all with different names, each 7 characters long. I was able to change the extensions but it feels very clunky. I am positive there is a cleaner way to write the following (but its functioning, so no complaints on that note):</p>
  
  <pre><code>    import os, sys
      path = 'C:/Users/dana/Desktop/text_files_2/'
          for filename in os.listdir(path):
              if filename.endswith('.rtf'):
                  newname = filename.replace('.rtf', '.txt')
                  os.rename(filename, newname)
          elif filename.endswith('.py'):
                  newname = filename.replace('.py', '.txt')
                  os.rename(filename, newname)
          elif filename.endswith('.TEXT'):
                  newname = filename.replace('.TEXT', '.txt')
                  os.rename(filename, newname)
          elif filename.endswith('.text'):
                 newname = filename.replace('.text', '.txt')
                 os.rename(filename, newname)
  </code></pre>
  
  <p>I do still have a bit of a problem: </p>
  
  <ol>
  <li>the script currently must be inside my directory for it to run. <br /></li>
  <li><p>I can not figure out how to add "file_" to the start of each of the filenames [<em>you would think that would be the easy part</em>]. I have tried declaring newname as </p>
  
  <pre><code>newname = 'file_' + str(filename)
  </code></pre>
  
  <p>it then states filename is undefined.</p></li>
  </ol>
  
  <p>Any assistance on my two existing issues would be greatly appreciated.</p>