本文提供一個生產可用的腳本,使用 os 與 shutil 模組遞迴清空指定目錄,並說明關鍵參數與錯誤處理要點。
#!/usr/bin/env python
import os
import shutil
rootdir = "/home/zoer/aaa"
filelist = os.listdir(rootdir)
for f in filelist:
filepath = os.path.join(rootdir, f)
if os.path.isfile(filepath):
os.remove(filepath)
print(filepath + " removed!")
elif os.path.isdir(filepath):
shutil.rmtree(filepath, True) # True = ignore_errors
print("dir " + filepath + " removed!")
True 表示遇錯誤(如權限不足、檔案被鎖定)自動略過,不拋出例外。def clear_directory(path):
for item in os.listdir(path):
item_path = os.path.join(path, item)
if os.path.isfile(item_path) or os.path.islink(item_path):
os.unlink(item_path)
else:
shutil.rmtree(item_path, ignore_errors=True)
ignore_errors=True 可避免腳本中斷,但殘留檔案需人工清理。os.path.islink 檢測後用 os.unlink 刪除連結本身而非目標。os.scandir() (Python 3.5+) 替代 listdir 減少系統呼叫。