本代码最原始的部分,来自于署名为 肖泽云 先生的博客(http://blog.csdn.net/xwebsite/article/details/4861084)
特此说明
不过本代码经过我修改,增加功能,代码行数扩展两倍多,添加了替换文件名中字符串的功能。
例如把批量的文件名“今天aa.txt 今天bb.txt”替换为“明天aa.txt 明天bb.txt”
然后修改代码,增加usage,添加命令行部分的识别,基本完成我想要的功能了⋯⋯
import os
import sys
def serial(arg, dirname, names):
fileNum=len(names)
eNum=1
tempfileNum=fileNum+arg["start"]
while tempfileNum/10>=1:
eNum+=1
tempfileNum=tempfileNum/10.0
print "File counts:",fileNum
i=arg["start"]
for file in names:
if file.startswith(".") == True:
continue
fileIndex=str(i)
fileIndex=fileIndex.zfill(eNum)
filesuffix = ""
dotindex = file.rfind(".")
if ((len(file)-dotindex) < 6) and (dotindex != -1):
filesuffix = file[dotindex:]
print "Edit:"+file+"-->"+arg["prefix"] + fileIndex + filesuffix
file=dirname+"/"+file
newName=dirname+"/"+arg["prefix"] + fileIndex + filesuffix
os.rename(file,newName)
print "Finish!"
i+=1
def replace(oldnew, dirname, names):
fileNum=len(names)
print "File counts:",fileNum
for file in names:
if file.startswith(".") == True:
continue
if file.find(oldnew["old"]) == -1:
continue
newfile = file.replace(oldnew["old"],oldnew["new"])
print "Edit: "+file+"-->" + newfile
file = dirname+"/"+file
newfile = dirname+"/"+newfile
os.rename(file,newfile)
print "Finish!"
def serialModel(path):
print "serial model"
arg = {}
arg["prefix"] = raw_input("Please input a prefix (eg. newfile):\n")
arg["start"]=int(raw_input("Please input start number (eg. 0):"))
print "New files form :"+arg["prefix"]+str(arg["start"])
doOrNot=raw_input("Are you sure(Y/N) :")
if doOrNot=="Y" or doOrNot=="y":
os.path.walk(path, serial, arg )
def replaceModel(path):
print "replace model"
oldnew = {}
oldnew["old"] = raw_input("Please input a old string:\n")
if oldnew["old"] == "" :
print "Old string cannot be empty\n"
os._exit(1)
oldnew["new"] = raw_input("Please input a new string:\n")
doOrNot=raw_input("Are you sure(Y/N) :")
if doOrNot=="Y" or doOrNot=="y":
os.path.walk(path, replace, oldnew)
def PrintUsage():
print "usage: python " + sys.argv[0] + " [ -r | -s | -h ] target_directory"
def PrintHelp():
PrintUsage()
print "-r : into replace model.replace file name use new string instead old string"
print "\t eg. old string is 'aa',new string is 'bb',file 'aabcd' will be 'bbbcd'"
print "-s : into serial model.replace file name use serial"
print "\t eg. 'aa.txt bb.txt' to '1.txt 2.txt'"
print "-h : show this help information"
def main():
path = ""
mod = "-r"
if len(sys.argv) < 2 or len(sys.argv) > 3:
PrintUsage()
return
elif len(sys.argv) == 2:
path = sys.argv[1]
elif len(sys.argv) == 3:
mod = sys.argv[1]
path = sys.argv[2]
if path == "-h":
PrintHelp()
os._exit(0)
if os.path.exists(path)==False:
print "The directory is not exist!\n"
os._exit(1)
if mod == "-r":
replaceModel(path)
elif mod == "-s":
serialModel(path)
elif mod == "-h":
PrintHelp()
else:
PrintUsage()
if __name__ == "__main__":
main();