Python 刪除檔案

永久刪除檔案

    
import os

file_path = "C:/Users/ruyut/Downloads/file.docx"

if os.path.exists(file_path):
    os.remove(file_path)
    

刪除檔案(移動到資源回收桶)

需要使用第三方套件 Send2Trash 來將檔案移動到資源回收桶中

安裝套件:
    
pip install Send2Trash
    

使用示範:
    
import os
from send2trash import send2trash

file_path = "C:/Users/ruyut/Downloads/file.docx"

# 依照作業系統替換檔案路徑
file_path = os.path.normpath(file_path)

if os.path.exists(file_path):
    send2trash(file_path)
    

需要注意的是在 Windows 下 Send2Trash 套件需要使用 \ 才可以正常刪除,否則會出現找不到檔案的錯誤。也可以使用 os.path.normpath 函式自動依照作業系統替換。

永久刪除空資料夾

    
import os

file_path = "C:/Users/ruyut/Downloads/新增資料夾"

if os.path.exists(file_path):
    os.rmdir(file_path)
    

如果資料夾內有檔案或資料夾,就會拋出下面的錯誤,需要使用其他方式刪除:
    
OSError: [WinError 145] 目錄不是空的。
    

永久刪除資料夾

    
import os
import shutil

file_path = "C:/Users/ruyut/Downloads/新增資料夾"

if os.path.exists(file_path):
    shutil.rmtree(file_path)
    

留言