萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 遞迴刪除目錄下所有檔案與子目錄

本文提供一個生產可用的腳本,使用 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!")

關鍵模組與參數解析

  • os.listdir:取得目錄下所有項目(不含路徑)。
  • os.path.join:跨平台安全路徑拼接。
  • os.path.isfile / isdir:區分檔案與目錄。
  • os.remove:刪除單一檔案。
  • shutil.rmtree(path, ignore_errors=True):遞迴刪除目錄樹,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)

常見陷阱與最佳實踐

  • 權限不足:以管理員/root 執行或調整目錄 ACL。
  • 檔案被佔用:Windows 下常見,ignore_errors=True 可避免腳本中斷,但殘留檔案需人工清理。
  • 符號連結:os.path.islink 檢測後用 os.unlink 刪除連結本身而非目標。
  • 大量檔案效能:考慮 os.scandir() (Python 3.5+) 替代 listdir 減少系統呼叫。
copyright © 萬盛學電腦網 all rights reserved