Saturday, March 13, 2010

Renaming Files in a folder

i was reorganizing a bunch of my music and was thinking on some ways to make it go faster. I put together the beginnings of a renaming python script, right now it is searching a given directory and replacing whatever is passed in to it. Pretty simple at the moment but we will see where it goes.

I switched over to python 3.0 today as well, one of the things i noticed off the bat is that print command has changed. Instead of the old : print 'My Text' its now print('My Text')

Took me a little while to figure out why those commands weren't working but seems like its on track now.


import os
import os.path



def findReplace(find , replace, dir):
# dir = r'c:\Temp\\'
# find = '-'
# replace = ''


for file in os.listdir(dir):
print(file)
if find in file:
newName = file.replace( find , replace)
newName = newName.strip(' ')

print('New Name = %s' % newName)
print('File = %s' %file)
print('Directory + filename = %s' % (dir + '\\' +file))

if os.path.isfile(dir + file) == True:
os.rename(dir + file, dir + newName)
print('Full final File Name = ' + file)
def split(index , splitBy, dir):
for file in os.listdir(dir):
if splitBy in file:
splitList = file.split(splitBy)
print(splitList)
newName =splitList[index].lstrip(' ')
print(newName)
if os.path.isfile(dir + file) == True:
os.rename(dir + file, dir + newName)
print('Full final File Name = ' + file)
if __name__ == '__main__':
split(3 , '-' , r '')