import os
import os.path
import re
rootdir = "c:\Users\leidar\desktop\matlab"
rootnames=os.listdir(rootdir)

prog = re.compile(r'().tif')
name = re.compile(r'([-_ \w]+)')
for rt in xrange(len(rootnames)):
	filenames = os.listdir(rootdir + os.sep + rootnames[rt]) # 找到一级子目录
	for a in xrange(len(filenames)):
		if prog.search(filenames[a]) != None:
			if name.findall(filenames[a])[-2] == 'tif':
				newname = name.findall(filenames[a])[-3] + '.tif'
			else:
				newname = name.findall(filenames[a])[-2] + '.tif'
			path = rootdir + os.sep + rootnames[rt] + os.sep ;
			os.renames(path + filenames[a], path + newname)
			print 'change name from ',(path + filenames[a])
			print 'to ', (path + newname)
    #os.renames(path + os.sep + filenames[a],path + os.sep + str(a)+'.bmp')