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

本文介绍了一种在Python中批量删除多级目录下文件及文件夹的方法,通过结合使用os和shutil模块,实现了不论目录层次多深都能一次性清空并删除的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值