python 实现彻底删除文件夹和文件夹下的文件

python 中有很多内置库可以帮忙用来删除文件夹和文件,当面对要删除多个非空文件夹,并且目录层次大于3层以上时,仅使用一种内置方法是无法达到彻底删除文件夹和文件的效果的,比较low的方式是多次调用直到删除。但是,我们可以结合多个内置库函数,达到一次删除非空文件夹,不管其目录层次有多深。

import os
import shutil
import traceback
import globalvar
def misc_init()

    # clean the test result folder
    # get the current path
    current_path = os.path.split(os.path.realpath(__file__))[0]
    # some folder not delete
    except_folders = globalvar.Except_Folders
    # get the folder uder current path 
    current_filelist = os.listdir(current_path)
    for f in current_filelist:
     # f should be a absolute path, if python is not run on current path if os.path.isdir(os.path.join(current_path,f)): if f in except_folders: continue else: real_folder_path = os.path.join(current_path, f) try: for root, dirs, files in os.walk(real_folder_path): for name in files: # delete the log and test result del_file = os.path.join(root, name) os.remove(del_file) logger.info('remove file[%s] successfully' % del_file) shutil.rmtree(real_folder_path) logger.info('remove foler[%s] successfully' % real_folder_path) except Exception, e: traceback.print_exc()

主要步骤:

1、利用os.listdir列出当前路径下的文件夹,根据需要可以跳过不想删除的文件夹

2、利用os.walk可以递归遍历当前路径文件夹内的文件,利用os.remove删除掉文件

3、使用shutil.retree递归删除掉这些空文件夹

注意:思想是先删除掉文件目录树下的所有文件,然后在递归删除掉空文件夹。globalvar是自定义的全局变量文件,非python库

原文地址:https://www.cnblogs.com/linyihai/p/6239067.html