zoukankan      html  css  js  c++  java
  • 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库

  • 相关阅读:
    React网络请求fetch之get请求
    英语学习
    人物传记
    四月
    启程
    情绪
    办公新址
    孩子大了
    幸福的生日
    hibernate---树状映射
  • 原文地址:https://www.cnblogs.com/linyihai/p/6239067.html
Copyright © 2011-2022 走看看