天天看点

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()