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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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:<br>     # 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库

posted @   yihailin  阅读(52999)  评论(1编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示