Python和perl实现批量对目录下电子书文件重命名的代码分享
经常会遇到下载的文件或电子书,名字中间都包含了一些网址信息,实际使用中由于名字太长不方便,下面的脚本使用正则表达式来对目录下的所有文件重命名:
例如:
修改前:[毛票票]MacOSXforUnixGeeks[www.nhooo.com].mobi
修改后:MacOSXforUnixGeeks.mobi
python代码如下:
importos importre
defrename_dir(dir,regex,f): ifnotos.path.isdir(dir)ornotos.path.exists(dir): print("Theinputisnotonedirectoryornotexist.") forroot,subdirs,filesinos.walk(dir): fornameinfiles: oldname=name newname=re.sub(regex,f,name) print("Before:"+os.path.join(root,oldname)) print("After : "+os.path.join(root,newname)) ifnotname==newnameandnotos.path.exists(os.path.join(root,newname)): os.rename(os.path.join(root,oldname),os.path.join(root,newname)) fordirinsubdirs: rename_dir(os.path.join(root,dir))
rename_dir("C:\\Python31\\test","\[.*\](.*)\[www.nhooo.com\](.*)",lambdam:m.group(1)+m.group(2))