《Python編程快速上手》第9.8.3實踐練習

#9.8.3 消除缺失的編號 
"""
1.spam001.txt,spam002.txt,spam005.txt,如此。將前邊的消除,然後後邊逐一遞增
2.空出一些編號,指定空出區域。然後修改編號。
"""

import re,os,shutil
#find_path=input("輸入要查找的目錄:")
#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))

#空餘值設計,不做過多類型及數值區域判斷,輸入區域符合正常範圍
space=input("請確認是否留下空白區,以備後用(Y/N)")
#預留配對修改名爲字典
chname_list={}
if space.lower()=='y':
    rang1=input("輸入空白區的起始值(包含此值爲空):")
    rang2=input("輸入空白區的結束值(包含此值爲空):")
    rang=range(int(rang1),int(rang2)+1)
    rang=list(rang)
    print("留空區爲:"+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") 

#對字典進行操作move
os.chdir(find_path)
for k,v in chname_list.items():
    shutil.move(k,v)
    print("move {} to {}".format(k,v))

print("done")    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章