Python下刪除檔案與資料夾(目錄)

2021-06-19 13:49:55 字數 411 閱讀 3692

比較傳統的,是使用os模組,

刪除檔案

os.remove()

刪除空目錄

os.rmdir()

遞迴刪除父目錄

os.removedirs() #當子目錄為空,將遞迴刪除給定父目錄,否則丟擲異常

但是若需要刪除的是非空目錄時,則需要通過遞迴逐一刪除檔案後再刪除目錄

網上有人通過system命令來實現,但是不同作業系統下會有區別:

windows系統下

os.system("rmdir /s /q directory")

linux系統下

os.systme("rm -rf directory")

另外相對快捷的就是使用shutil模組來刪除非空目錄或資料夾

shutil.rmtree(path)

Python 刪除檔案與資料夾

要刪除乙個檔案,需匯入os模組,使用其中的os.remove 函式 示例 刪除檔案 test.txt import os os.remove test.txt 為了避免出錯,需要在刪除之前檢查檔案是否存在 示例 刪除前檢查檔案是否存在 import os if os.path.exists test...

Python 刪除檔案 資料夾

import os filepath 需要刪除的檔案路徑 if os.path.exists filepath os.remove filepath else print 該檔案不存在 import os folderpath 需要刪除的資料夾路徑,該資料夾必須為空資料夾 if os.path.ex...

python 刪除資料夾 刪除非空資料夾

一般刪除檔案時使用os庫,然後利用os.remove path 即可完成刪除,如果刪除空資料夾則可使用os.removedirs path 即可,但是如果需要刪除整個資料夾,且資料夾非空時使用os.removedirs path 就會報錯了,此時可以使用shutil庫,該庫為python內建庫,是乙...