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庫
