在日常工作中,经常要批量重命名文件,python就可以代劳。看内容吧。
1 import os 2 3 perfix='Python' 4 5 length=2 6 base=1 7 format='mdb' 8 9 def PadLeft(str,num,padstr): 10 stringlength=len(str) 11 n=num-stringlength 12 if n>=0: 13 str=padstr*n+str 14 return str 15 16 print('the files in %s will be renamed'% os.getcwd()) 17 18 all_files=os.listdir(os.getcwd()) 19 20 print([f for f in all_files if os.path.isfile(f)]) 21 22 input=input('press y to continue \n') 23 24 if input.lower()!='y': 25 exit() 26 27 filenames=os.listdir(os.curdir) 28 29 i=base-1 30 31 for filename in filenames: 32 i+=1 33 if filename !='rename.py'and os.path.isfile(filename): 34 name=str(i) 35 name=PadLeft(name,length,'0') 36 t=filename.split('.') 37 m=len(t) 38 39 if format =='': 40 os.rename(filename,perfix+name+'.'+t[m-1]) 41 else: 42 if t[m-1] == format: 43 os.rename(filename,perfix+name+'.'+t[m-1]) 44 else: 45 i=i-1 46 else: 47 i=i-1 48 49 all_files=os.listdir(os.getcwd()) 50 print([f for f in all_files if os.path.isfile(f)])