python 中有很多內建庫可以幫忙用來刪除資料夾和檔案,當面對要刪除多個非空資料夾,並且目錄層次大於3層以上時,僅使用一種內建方法是無法達到徹底刪除資料夾和檔案的效果的,比較low的方式是多次呼叫直到刪除。但是,我們可以結合多個內建庫函式,達到一次刪除非空資料夾,不管其目錄層次有多深。
import osimport 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庫
徹底刪除git 檔案 資料夾
前兩天不小心上傳了乙個大的資料夾,幾百兆左右,後來發現沒有必要放到git 上,然後再本地刪除後重新提交了一版,但是後來發現 重新clone的source檔案大小依然是幾百兆,跟原來沒有變化。後才經過查閱資料才知道,原來檔案一直存在於git倉庫中,便於你的恢復,普通的刪除並不能真的將檔案從倉庫中移除。...
centos徹底刪除資料夾 檔案命令
centos 徹底刪除資料夾 檔案命令 centos徹底刪除資料夾 檔案命令 centos 新建 刪除 移動 複製等命令 1.新建資料夾 mkdir 檔名 新建乙個名為test的資料夾在home下 view source1 mkdir home test 2.新建文字 在home下新建乙個test....
centos徹底刪除資料夾 檔案命令
分析 在上述命令中,如果tmp目錄已經存在,mv命令將移動hscripts資料夾 目錄下的所有檔案,目錄和子目錄到tmp目錄。如果沒有tmp目錄,它將重新命名 hscripts目錄為tmp目錄。這個命令移動當前目錄的file1.txt檔案和tmp資料夾 目錄的file2.txt檔案到newdir目錄...