This question is a follow-up to this post: Python - rename files in subfolders based on subfolder and file name.
I am trying to loop through files within subfolders within C:\temp\
, and rename each file in a specified way. Below is the code I have so far:
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.
When I run the line, print "My_"+last+"_"+i ...
, it correctly shows that a file named VA1122F.A14
saved in C:\temp\11182014\
will be renamed
My_F_VA1122F_11182014.A14
.
However, the os.rename command returns this error:
"must be string, not list."
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 old 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.
I also tried these but each returned an error:
os.rename(os.path.join(root, filename),"My_"+last+"_"+i[0]+"_"+root.split("/")[-1]+"."+i[1])
Error: Returns the folder where python is installed and an error about a string as left operand.
os.rename(root + os.sep + filename,"My_"+last+"_"+i[0]+"_"+root.split("/")[-1]+"."+i[1])
Error: cannot concatenate 'str' amd 'list' objects
I have scoured the documentation and many posts but cannot figure out what I'm missing. Thank you for any help.