因为用matlab搞数字图像处理时文件是在麻烦..文件名都是Fig0203(a)(chest-xray).tif
这样的,于是用python写了一个正则来修改成chest-xray.tif
这样
正则表达式初学笔记 相关操作文件夹及代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 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)
|