如何用 Python 刪除目錄中的多個檔案?
你可以在 os 模組中使用函式刪除單個檔案或單個空資料夾。
示例
例如,如果你想刪除一個檔案 my_file.txt,
>>> import os
>>> os.remove('my_file.txt')os.remove 的引數可以是絕對路徑或相對路徑。
要刪除多個檔案,只需迴圈你的檔案列表並使用上述函式。如果你想刪除包含你要刪除的所有檔案的資料夾,你可以按如下方式刪除該資料夾
>>> import shutil
>>> shutil.rmtree('my_folder')示例
你還可以使用正則表示式刪除匹配模式的檔案。例如,
import os, re, os.path pattern = "^your_regex_here$" mypath = "my_folder" for root, dirs, files in os.walk(mypath): for file in filter(lambda x: re.match(pattern, x), files): os.remove(os.path.join(root, file))
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP