title: Python - rename files in subfolders based on subfolder and file name II
body: <p>This question is a follow-up to this post: <a href="https://stackoverflow.com/questions/31435984/python-rename-files-in-subfolders-based-on-subfolder-and-file-name">Python - rename files in subfolders based on subfolder and file name</a>.</p>
  
  <p>I am trying to loop through files within subfolders within <code>C:\temp\</code>, and rename each file in a specified way. Below is the code I have so far:</p>
  
  <pre><code>begin program.
  import os
  path = "C:/temp/"
  
  for root,dirname,filename in os.walk(path):   
       for i in filename:
          i = i.split(".")
          first = i[1][0]
          last = i[0][-1]       
          #print filename  
          print "My_"+last+"_"+i[0]+"_"+root.split("/")[-1]+"."+i[1]
          os.rename(filename,"My_"+last+"_"+i[0]+"_"+root.split("/")[-1]+"."+i[1])
  end program.
  </code></pre>
  
  <p>When I run the line, <code>print "My_"+last+"_"+i ...</code>, it correctly shows that a file named <code>VA1122F.A14</code> saved in <code>C:\temp\11182014\</code> will be renamed 
  <code>My_F_VA1122F_11182014.A14</code>. </p>
  
  <p>However, the os.rename command returns this error:</p>
  
  <blockquote>
    <p>"must be string,  not list."</p>
  </blockquote>
  
  <p>This seems be due to my use of "filename" in the os.rename command. From what I've read, the first argument for os.rename should be the <em>old</em> filename. When I run "print filename," it does indeed return a list of all files in the given subfolder, so that error makes sense. I just can't seem to figure out how to grab the old file name one at a time. </p>
  
  <p>I also tried these but each returned an error:</p>
  
  <pre><code>os.rename(os.path.join(root, filename),"My_"+last+"_"+i[0]+"_"+root.split("/")[-1]+"."+i[1])
  </code></pre>
  
  <blockquote>
    <p>Error: Returns the folder where python is installed and an error about
    a string as left operand.</p>
  </blockquote>
  
  <pre><code>os.rename(root + os.sep + filename,"My_"+last+"_"+i[0]+"_"+root.split("/")[-1]+"."+i[1])
  </code></pre>
  
  <blockquote>
    <p>Error: cannot concatenate 'str' amd 'list' objects</p>
  </blockquote>
  
  <p>I have scoured the documentation and many posts but cannot figure out what I'm missing. Thank you for any help.</p>