天天看點

python遞歸删除指定目錄下的所有檔案

#OS中檔案夾相關操作
#建立檔案夾 os.mkdir(path)
#擷取目前檔案夾目錄 os.getcwd()
#改變預設目錄 os.chdir(path)
#擷取目錄清單os.listdir(path)
#删除檔案夾 os.rmdir(path)


import os

def deleteFolder( folderPath ):
    #反向查找傳入的檔案夾路徑最後一個字元是否為斜杠
    pos = folderPath.rfind("/")
    if pos>0:
       #如果檔案夾路徑最後一個字元不是斜杠,則在末尾添加斜杠
       folderPath = folderPath+'/'
    
    try:
        #擷取目前檔案夾下檔案清單,包括檔案和檔案夾
        childList = os.listdir(folderPath)
    except Exception as e:
        return e, -1
    #如果檔案夾清單為空,傳回異常
    if childList is None:
        print("檔案夾不合法")
        return "error", -2

    #便利目前檔案夾下檔案名稱清單
    for child in childList:
        #根據判斷檔案有沒有*.*的字尾,區分是檔案還是檔案夾
        isFile = child.rfind('.')
        if isFile>0:
           #如果是檔案,對檔案進行删除
           os.remove(folderPath+child)
        else:
           #如果是目錄進行遞歸便利
           deleteFolder( folderPath+child )

    #遞歸結束後檔案夾已經是空檔案夾,直接删除空檔案夾
    os.rmdir(folderPath)
    return "OK", 0

def main(): 

    ret =deleteFolder(r"D:/DRIVER/ETC/Log/2018-09-28")

    print(ret)

    if ret[1]!=0:
       print("檔案夾删除異常,錯誤資訊[%s]" %ret[0])
    else:
       print("檔案夾删除成功")

if __name__ == '__main__':
    main()