← 從零開始學 Python
第 78 課,共 78 課 · 10 XP
刪除檔案
理論與題目說明
機器翻譯,尚未經母語人士審閱。
刪除和檢查檔案用的是 os 模組:
import os
os.path.exists("notes.txt") # 檔案(或資料夾)是否存在
os.path.isfile("notes.txt") # 真的是檔案嗎?
os.remove("notes.txt") # 刪除檔案
os.listdir(".") # 資料夾裡的檔案清單
os.mkdir("backup") # 建立資料夾
os.rmdir("backup") # 刪除空資料夾
刪除無法復原:沒有資源回收筒,檔案會立刻消失。
檔案不存在時,os.remove 會引發 FileNotFoundError。有兩種做法:
# 1. 先檢查
if os.path.exists(path):
os.remove(path)
# 2. 直接做,再攔截錯誤
try:
os.remove(path)
except FileNotFoundError:
pass
第二種比較可靠:在檢查和刪除之間,檔案也可能消失。Python 把這種風格叫做 EAFP:「請求原諒比請求許可容易」。
os 模組的現代替代品是 pathlib:Path("notes.txt").unlink(missing_ok=True)。
題目。 寫一個函式 safe_delete(path):刪除檔案並回傳 True;檔案不存在時不要停止,而是回傳 False。