#9.8.3 Remove missing number "" "1.spam001.txt,spam002.txt,spam005.txt, so. Remove the front and then increment by 2. Some numbers are vacated, and the vacated areas are specified. Then change the numbering. "" "Import re,os,shutil#find_path=input (" Enter the directory to find: ") #find_path =os.path.abspath (Find_path) find_path= Os.path.abspath ("D:\pytest") Filenamereg=re.compile (r "(Spam (\d+) \.txt$)") #将合格的文件名添加为列表file_list =[]for name in Os.listdir (Find_path): Reg_name=filenamereg.search (name) if Reg_name:file_list.append (Reg_name.group (1)) #空余值设计, Do not do too many types and the value of the region to judge, the input area to meet the normal range space=input ("Please confirm whether to leave a blank area for later use (y/n)") #预留配对修改名为字典chname_list ={}if space.lower () = = ' Y ': rang1 =input ("Enter the starting value of the white space (including this value is NULL):") rang2=input ("Enter the end value of the white space (including this value is empty):") rang=range (int (rang1), int (rang2) +1) rang=list (rang Print ("Empty area is:" +str (rang)) #将需要处理的文件名配对为字典 list1= file_list[:rang[0]-1].copy () for file in List1:print (List1.index ( file) filename= "spam" +str (list1.index (file) +1). Rjust (3, ' 0 ') + ". txt" chname_list[file]=filename list2= file_list[ Rang[0]-1:].copy () for file in list2:filename= "spam" +str (list2.index (file) +rang[-1]+1). Rjust (3, ' 0 ') + ". txt" chname_ List[file]=filenAme elif space.lower () = = ' n ': #将需要处理的文件名配对为字典 for file in file_list:filename= "spam" +str (file_list.index (file) +1). Rjust (3, ' 0 ') + ". txt" chname_list[file]=filename else:print ("Input error") #对字典进行操作moveos. ChDir (Find_path) for k,v in Chname_ List.items (): Shutil.move (k,v) print ("move {} to {}". Format (K,V)) print ("Done")
Python programming Quick Start "9.8.3 practice exercise